In my app want to round a double to 2 significant figures after decimal point. I tried the code below.
public static double round(double value, int places) {
long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}
also i tried
double val = ....;
val = val*100;
val = (double)((int) val);
val = val /100;
both code do not working for me.
Thanks in advance....
As Grammin said, if you're trying to represent money, use BigDecimal. That class has support for all sorts of rounding, and you can set you desired precision exactly.
But to directly answer your question, you can't set the precision on a double, because it's floating point. It doesn't have a precision. If you just need to do this to format output, I'd recommend using a NumberFormat. Something like this:
NumberFormat nf = NumberFormat.getInstance();
nf.setMinimumFractionDigits(2);
nf.setMaximumFractionDigits(2);
String output = nf.format(val);
Or you can use a java.text.DecimalFormat:
String string = new DecimalFormat("####0.00").format(val);
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