-1

I'm trying to use this code to get number 2.90 printed from the intial number 2.90689:

double number = 2.90689;
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.FLOOR);  //error
System.out.println(df.format(number));

However I get the Usage of API documented as @since 1.6+ error when trying to set rounding mode. How do I solve this in a modern way? All answers I've found use this seemingly deprecated code.

PS: It's not an error, but a warning in IDE. When run, it also doesn't work properly: prints 2.9 instead of 2.90. I've made this repl: https://repl.it/repls/IllInterestingComputers.

Screenshot of the warning: enter image description here

parsecer
  • 4,758
  • 13
  • 71
  • 140

2 Answers2

3
double number = 2.90689;
DecimalFormat df = new DecimalFormat("#.00");
df.setRoundingMode(RoundingMode.FLOOR);  //error
System.out.println(df.format(number));

Please check https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

0   Number  Yes Digit
#   Number  Yes Digit, zero shows as absent
dassum
  • 4,727
  • 2
  • 25
  • 38
0

You should use BigDecimal, heres an example:

double number = 2.90689;
BigDecimal roundedDown = BigDecimal.valueOf(number).setScale(2, RoundingMode.DOWN);
System.out.println("Original: " + number);
System.out.println("Rounded: " + roundedDown);

Stdout:

Original: 2.90689
Rounded: 2.90
J11
  • 426
  • 1
  • 6
  • 17