3
DecimalFormat hisFormat = new DecimalFormat("########.##");
hisFormat.setRoundingMode(RoundingMode.DOWN);

Float x=12345678.12345f;
System.out.println("Float Value " + hisFormat.format(x));

Above code print "Float Value" as 12345678 I need 12345678.12

How can I get my result? Please let me know.

user207421
  • 305,947
  • 44
  • 307
  • 483
Shailendra
  • 347
  • 6
  • 21
  • Multiply your number by 100. Round it. Divide by 100 and then print it. – Luud van Keulen Feb 15 '17 at 22:01
  • 2
    @LuudvanKeulen That's the [wrong way to do it](http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java#comment17119801_153753). – 4castle Feb 15 '17 at 22:04
  • 2
    @LuudvanKeulen Floating-point numbers are stored in base-2, not base-10, so the multiplication introduces rounding errors which often produces an incorrect result. – 4castle Feb 15 '17 at 22:06
  • 1
    This isn't really a duplicate. The reason the value is printing as `12345678` is because `float`s can't hold 13 significant digits of precision. If `x` was `5678.1234`, you would indeed see `5678.12` printed out. You should use a `double` if you need more than 8 or so significant digits of precision. – GriffeyDog Feb 15 '17 at 22:13
  • @LuudvanKeulen For proof that it's wrong see [here](http://stackoverflow.com/a/12684082/207421). – user207421 Feb 15 '17 at 22:15
  • @GriffeyDog Agreed. Also the OP is already using a decimal radix, which is what all the correct answers in the alleged duplicate recommend. Reopened. However it is certainly a duplicate of some other question involving invalid `float` ranges. – user207421 Feb 15 '17 at 22:49

1 Answers1

1

Use Double other than Float, or you will lose precision

DecimalFormat hisFormat = new DecimalFormat("######.##");
hisFormat.setRoundingMode(RoundingMode.DOWN);
Double x = 12345678.12345;
System.out.println("Float Value " + hisFormat.format(x));

Use Float the result is 12345678

Use Double the result is 12345678.12

Haifeng Zhang
  • 30,077
  • 19
  • 81
  • 125