1

Pretty direct question. I'm looking to take an outputted number, and round it to 2 decimal places. It appears that I'm only able to truncate a number using maxFractionDigits (see code below)

How can I round a number to 2 decimal places?

<Input
    value="{
        path: 'helloPanel>/recipient/amount',
        type: 'sap.ui.model.type.Float',
        formatOptions: {
            minFractionDigits: 2,
            maxFractionDigits: 2
        }
    }"
    description="Hello {helloPanel>/recipient/name}"
    valueLiveUpdate="false"
    width="60%"
/>
0

1 Answer 1

3

You can achieve rounding easily by defining a specific rounding mode in the section /formatOptions/roundingMode.

Typically, the rounding mode is HALF_AWAY_FROM_ZERO by default. E.g. if the real value is 1.678, the output will be 1.68 (assuming maxFractionDigits: 2). However, if the real value is 1.671, the output will be 1.67 because HALF_* rounds always from 5 and upwards.

If you want the framework to round always away from zero (regardless whether the next digit of maxFractionDigits is higher than 4 or not), then your code would look like this:

<Input xmlns="sap.m"
  value="{
    path: 'helloPanel>/recipient/amount',
    type: 'sap.ui.model.type.Float',
    formatOptions: {
      maxFractionDigits: 2,
      roundingMode: 'AWAY_FROM_ZERO'
    }
  }"
/>

⚠️ Note: if the target SAPUI5/OpenUI5 version is lower than 1.85, assign the rounding mode string all in lowercase (AWAY_FROM_ZEROaway_from_zero). Otherwise, there will be a vague TypeError. This bug is fixed since 1.85: https://github.com/SAP/openui5/issues/2169


Rounding Modes

Here are some graphics showing the differences between the rounding modes.
See also the table in the section "Miscellaneous" of the topic "Number Format".

roundingMode: 'AWAY_FROM_ZERO'

±1.678 → ±1.68

UI5 rounding mode - AWAY_FROM_ZERO

roundingMode: 'TOWARDS_ZERO'

±1.678 → ±1.67

UI5 rounding mode - TOWARDS_ZERO

roundingMode: 'FLOOR'

"Towards negative infinity": -1.678 → -1.68 || 1.678 → 1.67

UI5 rounding mode - FLOOR

roundingMode: 'CEILING'

"Towards positive infinity": -1.678 → -1.67 || 1.678 → 1.68

UI5 rounding mode - CEILING

roundingMode: 'HALF_...'

One of the four rounding modes but only starting from 5+.
E.g. roundingMode: 'HALF_CEILING': -1.678 → -1.67 || 1.674 → 1.67 even if the mode was CEILING.



According to the NumberFormat reference, there is also a possibility to define your own mutator.

... [Rounding mode] can be assigned:

  • by value in RoundingMode,
  • via a function that is used for rounding the number and takes two parameters: the number itself, and the number of decimal digits that should be reserved.
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.