# Thread: Round off 2 decimal places

1. hi, how do i round off 2 decimal places in J2ME? i use s60 3rd edition phone... thanks

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

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

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

5. 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 banker's rounding. That is, if the fractional part is exactly 0.5, then you round up or 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 Code:
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 == 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'.');

if (negative) {

s.insert(0'-');
}

return
s.toString();
}
Graham.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•
Nokia Developer aims to help you create apps and publish them so you can connect with users around the world.