hi, how do i round off 2 decimal places in J2ME? i use s60 3rd edition phone... thanks
Printable View
hi, how do i round off 2 decimal places in J2ME? i use s60 3rd edition phone... thanks
First of all use Math.floor()
and the code goes roughly like this, unless I made a stupid mistake :-)
floor(x*100+0.5)/100
Hartti
hi hartti. i used math.ceil and math.floor but it rounds it off to a whole number.. i want it to be decimal to give the actual result with 2 decimal places...thanks anyway
Did you even read my response?
You multiply the number by 100, do the rounding and divide it back with 100. That gives you a number with two decimals.
Hartti
Do you want this for handling currency (money) amounts?
If you're handling money, you should never use a float or double. Instead, use a long, and store the number of 100ths of a penny (or cent, or whatever). That is €14.65 becomes 146500.
Reasons:
* Floating point numbers are inexact, and prone to bizarre rounding errors. Integers are precise.
* When performing calculations on money, you sometimes need two extra decimal places, to avoid compounding rounding errors. This is usual for currency conversions, or when adding tax.
Another thing to think about with money is that rounding is frequently [i]banker's rounding[/i]. That is, if the fractional part is exactly 0.5, then you round up [i]or[/i] down, ensuring that the result is an even number. This tends to balance out rounding errors since, in this case, rounding up or down are equally valid.
Example code:
[php]
private static String moneyToString(long money) {
boolean negative = money < 0;
if (negative) {
money = -money;
}
// round
int fraction = (int) money % 100;
money /= 100;
if (fraction > 50 || (fraction == 50 && money % 2 == 1)) {
money++;
}
StringBuffer s = new StringBuffer(Long.toString(money));
// pad
while (s.length() < 3) {
s.insert(0, '0');
}
// insert decimal place
s.insert(s.length() - 2, '.');
// add sign
if (negative) {
s.insert(0, '-');
}
return s.toString();
}
[/php]
Graham.