Reputation: 539
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....
Upvotes: 7
Views: 19777
Reputation: 1328
I took the decision to use all as int. In this way no problem.
DecimalFormatSymbols currencySymbol = DecimalFormatSymbols.getInstance();
NumberFormat numberF = NumberFormat.getInstance();
after...
numberF.setMaximumFractionDigits(2);
numberF.setMinimumFractionDigits(2);
TextView tv_total = findViewById(R.id.total);
int total = doYourStuff();//calculate the prices
tv_total.setText(numberF.format(((double)total)/100) + currencySymbol.getCurrencySymbol());
Upvotes: 0
Reputation: 48186
Or you can use a java.text.DecimalFormat:
String string = new DecimalFormat("####0.00").format(val);
Upvotes: 6
Reputation: 5585
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);
Upvotes: 20
Reputation: 23169
Your code appears to work to me
double rounded = round(0.123456789, 3);
System.out.println(rounded);
>0.123
Edit: just seen your new comment on your question. This is a formatting problem, not a maths problem.
Upvotes: 0
Reputation: 2739
As Gramming suggested you could use BigDecimals for that, or NumberFormat tobe sure about the number of shown figures
Upvotes: 0
Reputation: 12205
I would recommend using BigDecimal if you are trying to represent currency.
This example may be helpful.
Upvotes: 3