Skip to content

Formatting Quantities: maxFractionDigits are ignored #444

@einsweniger

Description

@einsweniger

I'm trying to use the Library for formatting numbers up to a specific length in decimal places.
Example given: use 3.0001 and print it with up to 4 or 2 fraction digits, yielding 3.0001 and 3 respectively.

Example:

    val floorAfter4Digits = NumberFormat.getNumberInstance().apply {
      maximumFractionDigits = 4
      roundingMode = RoundingMode.FLOOR
    }
    val floorAfter2Digits = NumberFormat.getNumberInstance().apply {
      maximumFractionDigits = 2
      roundingMode = RoundingMode.FLOOR
    }

Using the same logic, I'd like to format Quantities (outputting "3.0001 N" and "3 N") by re-using the number formatting from above:

    val floorQuantityAfter4Digits = NumberDelimiterQuantityFormat
      .builder()
      .setNumberFormat(floorAfter4Digits) // <-- reusing formatter from above
      .setUnitFormat(SimpleUnitFormat.getInstance())
      .build()
    val floorQuantityAfter2Digits = NumberDelimiterQuantityFormat
      .builder()
      .setNumberFormat(floorAfter2Digits) // <-- reusing formatter from above
      .setUnitFormat(SimpleUnitFormat.getInstance())
      .build()

Now, just formatting numbers yields the correct result, but the Quantities are not formatted correctly:

    val double30001 = 3.0001
    val quantity30001 = Quantities.getQuantity(double30001, Units.NEWTON)
    assertEquals("3.0001", floorAfter4Digits.format(double30001)) //
    assertEquals("3", floorAfter2Digits.format(double30001)) //
    assertEquals("3.0001 N", floorQuantityAfter2Digits.format(quantity30001)) //
    assertEquals("3 N", floorQuantityAfter4Digits.format(quantity30001)) //
    // ^--- org.opentest4j.AssertionFailedError: expected: <3 N> but was: <3.0001 N>

The last test fails, which is unexpected. Am I using this wrong, somehow? Or is this a bug?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status
    ✅ Done

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions