Possible Duplicate:
Round a double to 2 significant figures after decimal point
how to convert double to 2 number after the dot ?
for example:
double x=123.45678;
i need that x=123.45
(in java for android)
thanks in advance
Possible Duplicate:
Round a double to 2 significant figures after decimal point
how to convert double to 2 number after the dot ?
for example:
double x=123.45678;
i need that x=123.45
(in java for android)
thanks in advance
x = Math.floor(x * 100) / 100;
try this code
double x=123.45678;
DecimalFormat df = new DecimalFormat("#.##");
String dx=df.format(x);
x=Double.valueOf(dx);
use this,
NumberFormat formatter = new DecimalFormat("#0.00");
x=formatter.format(x);
Use NumberFormat class for correct formatting of numbers.
Specifically in your case you can do the following. Although this is not ver L10N friendly.
mNumberFormat = NumberFormat.getInstance();
mNumberFormat.setMinimumFractionDigits(2);
mNumberFormat.setMaximumFractionDigits(2);
The best way to format a double is with the NumberFormat class: http://developer.android.com/reference/java/text/NumberFormat.html
You'll be doing something like this:
NumberFormat nf = NumberFormat.getInstance(); // get instance
nf.setMaximumFractionDigits(2); // set decimal places
String s = nf.format(x);
You can also cast it back to a double.
If you want to get two digits correctly rounded, I would go with BigDecimals:
BigDecimal bd = new BigDecimal(x);
System.out.println(bd.setScale(2,BigDecimal.ROUND_HALF_EVEN).toPlainString());