# Round off 2 decimal places

• 2011-02-01, 19:28
binsint
Round off 2 decimal places
hi, how do i round off 2 decimal places in J2ME? i use s60 3rd edition phone... thanks
• 2011-02-02, 05:57
hartti
Re: Round off 2 decimal places
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
• 2011-02-02, 09:09
binsint
Re: Round off 2 decimal places
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
• 2011-02-02, 17:09
hartti
Re: Round off 2 decimal places
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
• 2011-02-02, 20:09
grahamhughes
Re: Round off 2 decimal places
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));

while (s.length() < 3) {
s.insert(0, '0');
}

// insert decimal place
s.insert(s.length() - 2, '.');