-1

What is the best way to get a float value rounded to two decimal digits?

For example, I have float f1 = 123.9876.
But I need 123.98.

Are there any annotations which can do this?

Pamasich
  • 63
  • 1
  • 9
Parminder Singh
  • 131
  • 3
  • 10

1 Answers1

1

You can do it manually with BigDecimal Class

float f=123.456778f;
BigDecimal decimalNo=new BigDecimal(f);
decimalNo=decimalNo.setScale(2,BigDecimal.ROUND_HALF_UP);

decimalNo = 123.45

Tarun
  • 986
  • 6
  • 19
  • 1
    Yes, indeed, it will work with BigDecimal. Note that floating point types like float or double will not necessarily succeed. With FP values, one usually doesn't round the *value*, just its *output* (i.e. the conversion to string), using one of the many ways to round output. – Rudy Velthuis Aug 13 '18 at 14:47
  • 1
    FWIW, it may make sense to use `BigDecimal decimalNo = BigDecimal.valueOf(f);` instead of `new BigDecimal(f);`. But see https://stackoverflow.com/questions/7186204/bigdecimal-to-use-new-or-valueof – Rudy Velthuis Aug 13 '18 at 14:49
  • 1).Rounding can be required when any one want to store value in DataBase or file. and 2). Yes you are right, valueOf() will make more sense here. – Tarun Aug 14 '18 at 05:44
  • even if you store in a DB or file, you are still rounding the output (OK, not just conversion to string -- to anything suitable), not the original value. – Rudy Velthuis Aug 14 '18 at 07:07
  • In DB double values are saved in number format not in String. (It is good to convert it in string but rounding is required to original value when it is required, Both options are situational) – Tarun Aug 14 '18 at 07:15