The double parameter on the line giving the wrong result

In my project, I get string values ​​from api and you need to pass double values ​​to another api. When I try to parse string values ​​to double, I don't get the raw data.

Here is the code.

String l1="11352721345377306"; String l2="11352721346734307"; String l3="11352721346734308"; String l4="11352721346734309"; DecimalFormat df = new DecimalFormat(".00"); System.out.println(df.format(Double.parseDouble(l1))); System.out.println(df.format(Double.parseDouble(l2))); System.out.println(df.format(Double.parseDouble(l3))); System.out.println(df.format(Double.parseDouble(l4))); 

Output signal

 11352721345377306.00 11352721346734308.00 11352721346734308.00 11352721346734308.00 

Something went wrong? Is there a problem with parsing? How to return the original values?

Edit : without using decimal format:

 1.1352721345377306E16 1.1352721346734308E16 1.1352721346734308E16 1.1352721346734308E16 
+5
source share
4 answers

You cannot return the original values. See Java (Im) floating point precision .

+8
source

double has only 15/16 digits of precision, and when you give it a number that it cannot represent, it takes the closest represented number.

+4
source

What is the problem? ".00"? If you don’t need it, why use Double?

You can try like this ...

  String l1="11352721345377306"; String l2="11352721346734307"; String l3="11352721346734308"; String l4="11352721346734309"; Double d1 = Double.parseDouble(l1); Double d2 = Double.parseDouble(l2); Double d3 = Double.parseDouble(l3); Double d4 = Double.parseDouble(l4); System.out.println(d1.longValue()); System.out.println(d2.longValue()); System.out.println(d3.longValue()); System.out.println(d4.longValue()); 

Modify using BigDecimal to get the correct values:

  String l1="11352721345377306"; String l2="11352721346734307"; String l3="11352721346734308"; String l4="11352721346734309"; BigDecimal bd1 = new BigDecimal(l1); BigDecimal bd2 = new BigDecimal(l2); BigDecimal bd3 = new BigDecimal(l3); BigDecimal bd4 = new BigDecimal(l4); System.out.println(bd1); System.out.println(bd2); System.out.println(bd3); System.out.println(bd4); 

Output:

 11352721345377306 11352721346734307 11352721346734308 11352721346734309 
0
source

you can use

 double d = Math.round(Double.parse(yourString) * 100.0) / 100.0; 

to get double rounding with rounded decimal places.

To print, use:

 String formatted = String.format("%.2f", yourDouble); 
0
source

Source: https://habr.com/ru/post/1239424/


All Articles