Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android number format

Tags:

java

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....

like image 741
upv Avatar asked May 12 '11 13:05

upv


2 Answers

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);
like image 132
Ian McLaird Avatar answered Sep 18 '22 09:09

Ian McLaird


Or you can use a java.text.DecimalFormat:

String string = new DecimalFormat("####0.00").format(val);
like image 38
ratchet freak Avatar answered Sep 20 '22 09:09

ratchet freak