Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any functions for truncating a double in java?

Tags:

java

Is there a Java Library function which can be used to truncate a number to an arbitrary number of decimal places? For Example.

SomeLibrary.truncate(1.575, 2) = 1.57

Thanks


2 Answers

Try setScale of BigDecimal like so:

public static double round(double d, int decimalPlace) {
    BigDecimal bd = new BigDecimal(d);
    bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP);
    return bd.doubleValue();
}
like image 161
raoulsson Avatar answered Sep 14 '25 08:09

raoulsson


Incredible no one brought this up yet, Java API has had DecimalFormat for ages now for this exact purpose.

like image 34
Esko Avatar answered Sep 14 '25 08:09

Esko