-5

String.format("%,.0f", 200000000000000000000000.0)

-> 199,999,999,999,999,980,000,000 why?

J. Murray
  • 1,460
  • 11
  • 19
  • Because of the precision of the internal representation. See [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken?r=SearchResults) – lurker Oct 07 '19 at 10:10
  • @LongNguyenVan you may look here for solution: https://stackoverflow.com/questions/48201462/store-big-price-value-in-database-along-with-decimal-point-in-sqlite-database – Bhoomika Patel Oct 07 '19 at 10:12

3 Answers3

0

Understand the Double Data type - it is an approximation of amount and scale.

The Following assignment:

double d = 2.00000000000f;

will generate a value of 1.9999999 at times when printed. What you are seeing here is magnification of that. Double Data types also have a maximum (implementation-dependant) of how many places of significance they can support (upto 15 generally) - which is why the last 6 digits are all zeros (0)

For your particular solution, if you don't require Floating-point Data, stick to Integer.

J. Murray
  • 1,460
  • 11
  • 19
0

It is because current processors(and most VMs) work like that if use default data types. Here it is explained in details

If you want precision use BigDecimal. This class is specifically intended for situations like this - to be used in currency related stuff and scientific calculations.

To format decimals in proper way Java has DecimalFormat

String pattern = "###,###.###";
DecimalFormat decimalFormat = new DecimalFormat(pattern);

String format = decimalFormat.format(123456789.123);
System.out.println(format); // -> 123.456.789,123

Here is nice tutorial about it

Hope it helps.

Pavlo Ostasha
  • 14,527
  • 11
  • 35
0

My problem has been solved

String.format("%,.0f", BigDecimal( 200000000000000000000000.0, MathContext.DECIMAL64))