This is probably a really simple question but, is there a simple way to go from
Double myLongNumber = 50.12345678998658576546
to
Double myLongNumber = 50.1234
?
I just want to reduce the number of decimal digits, not remove them all.
CodePudding user response:
If you really want to change that number, you can do something like
Double myNotSoLongNumber = Math.round(myLongNumber * 1E4) / 1E4;
If you want to display a Double with less fraction digits, use
String myLongNumberAsString = String.format("%.4f", myLongNumber);
CodePudding user response:
Please check below options
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Locale;
import org.apache.commons.math3.util.Precision;
class DoubleTrimmer {
public static void main(String[] args) {
Double myLongNumber = 50.12345678998658576546;
//Option1. just trim the number
Double trimmedNumber = Double.valueOf(String.format(Locale.ENGLISH, "%.4f", myLongNumber));
System.out.println(trimmedNumber);
//Option2. Round the number using BigDecimal
trimmedNumber = round(myLongNumber, 4);
System.out.println(trimmedNumber);
//Option3. Round the number using Apache commons math
trimmedNumber = Precision.round(myLongNumber, 4);
System.out.println(trimmedNumber);
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = BigDecimal.valueOf(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
}
CodePudding user response:
Use BigDecimal package
import java.math.BigDecimal;
public class ReduceDecimalNumbers {
public static void main(String args[]){
double myLongNumber = 50.12345678998658576546;
int decimalsToConsider = 4;
BigDecimal bigDecimal = new BigDecimal(myLongNumber );
bigDecimal = new BigDecimal(myLongNumber );
BigDecimal roundedValueWithDivideLogic = bigDecimal.divide(BigDecimal.ONE,decimalsToConsider,BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded value with Dividing by one = " roundedValueWithDivideLogic);
}
}
output:
Rounded value with Dividing by one = 50.1235
or you can try this
public class round{
public static void main(String args[]){
double myLongNumber = 50.12345678998658576546;
double roundOff = Math.round(myLongNumber *1E4)/1E4;
System.out.println(String.format("%.4f", roundOff)); //%.4f defines decimal precision you want
}
}
output:
50.1235