0

I have a project where I need to format numbers before print them. I do it like that:

public String formatNumber(String format, long number, RoundingMode roundingMode) {
    DecimalFormat df = new DecimalFormat(format);
    df.setRoundingMode(roundingMode);
    return df.format(number);
}

But my app need to use GWT, and I can't use DecimalFormat anymore because it's not supported. I need to use NumberFormat from the package com.google.gwt.i18n.client.NumberFormat;.

I format my numbers like that:

public String formatNumber(String format, long number, RoundingMode roundingMode) {
     NumberFormat df = NumberFormat.getFormat(format);
     return df.format(number);
 }

As you can see, df.setRoundingMode doesn't exist on NumberFormat. My number is automatically rounded to the nearest decimal. However, I do not always want to have this behavior. How can I round the numbers as I wish with this class?

Thanks

Benjamin Lucidarme
  • 1,648
  • 1
  • 23
  • 39

2 Answers2

0

GWT NumberFormat does not support rounding modes. BUT, you are formatting a long, so looks like you don't need rounding anyway. If you really need it, so you have some float, double, BigDecimal, etc. I recommend that you use BigDecimal and change the scale before calling the formatter.

NumberFormat.getDecimalFormat().format(new BigDecimal(1.123).setScale(2, RoundingMode.HALF_EVEN));

Or just...

String str = new BigDecimal(1.123).setScale(2, RoundingMode.HALF_EVEN).toPlainString();
Ignacio Baca
  • 1,538
  • 14
  • 18
0

You may want to have a look at Math.rint() and Math.round() See difference

You then would return Math.rint(df.format(number))

ArcTanH
  • 384
  • 2
  • 10