I have a series of Java decimals like:
0.43678436287643872
0.4323424556455654
0.6575643254344554
I wish to cut off everything after 5 decimal places. How is this possible?
Truncation Using Casting If our double value is within the int range, we can cast it to an int. The cast truncates the decimal part, meaning that it cuts it off without doing any rounding.
Shift the decimal of the given value to the given decimal point by multiplying 10^n. Take the floor of the number and divide the number by 10^n. The final value is the truncated value.
The DecimalFormat could also be of assistance here:
double d = 0.436789436287643872;
DecimalFormat df = new DecimalFormat("0.#####");
df.setRoundingMode(RoundingMode.DOWN);
double outputNum = Double.valueOf(df.format(d));
String outpoutString = df.format(d);
Double.parseDouble(String.valueOf(x).substring(0,7));
OR
Double.valueOf(String.valueOf(x).substring(0,7));
where x
contains the value you want to cut such as 0.43678436287643872
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With