简体   繁体   中英

How to format a string to double with respective decimal places and assign to double variable in Java

Background I am getting a scientific value (with exponential). I need to round off this to normal decimal value with two decimal points with double data type

I have done as below

DecimalFormat formatter = new DecimalFormat("0.00");
x.setByteFor95(Double.valueOf(formatter.format(x.getSrcToDestBytes())));

I get the below value while debugging

formatter.format(x.getSrcToDest95PercentileBytes())

16502416.10

But when converting to double it become scientific value again

Double.valueOf(formatter.format(x.getSrcToDest95PercentileBytes()))

1.65024161E7

How to get the double type value with two decimal places? I need to get double with two decimal places at the end

Formatting has little to do with the actual value of the number, however in your code where you parse it back to double, it should work if the rounded value can be represented exactly by a double. Note that an infinity of numbers cannot be represented accurately by a double, otherwise we would need an infinite amount of memory.

If you want arbitrary accuracy, you should use BigDecimal instead. And remember that the way the value is displayed when printing it might still be in scientific notation because this does not alter its value at all, formatting and the value are independent. Using BigDecimal , you will be able to control the rounding behavior finely, as you require.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM