Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cut off decimal in Java WITHOUT rounding?

Tags:

java

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?

like image 504
yazz.com Avatar asked Dec 13 '11 09:12

yazz.com


People also ask

How do you remove decimals without rounding in Java?

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.

How do you shorten a decimal in Java?

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.


2 Answers

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);
like image 69
Costis Aivalis Avatar answered Nov 05 '22 07:11

Costis Aivalis


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

like image 20
Kris Avatar answered Nov 05 '22 06:11

Kris