In my project I am getting a string values from an api and need to pass double values to another api. When I try to parse from string values to double I am not getting the original 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)));
The output is
11352721345377306.00
11352721346734308.00
11352721346734308.00
11352721346734308.00
What went wrong? Is there any problem with parsing? How can i get the original values back.?
Edit : Without using Decimal Format:
1.1352721345377306E16
1.1352721346734308E16
1.1352721346734308E16
1.1352721346734308E16
You can't get original values back. Refer this Java's Floating-Point (Im)Precision .
double
只有15/16位数的精度,当你给它一个它无法表示的数字时,它需要最接近的可表示数字。
What is the problem ? ".00" ? If you don't need this, why using a 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());
Edit, with 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 is:
11352721345377306
11352721346734307
11352721346734308
11352721346734309
You can use
double d = Math.round(Double.parse(yourString) * 100.0) / 100.0;
to get double with rounded decimals.
For printing use:
String formatted = String.format("%.2f", yourDouble);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.