SitePoint Sponsor

# Thread: Rounding Problem

1. ## Rounding Problem

Hello, I'm having a problem with rounding in a Javascript file. If an order comes up at 17.99 it rounds to 18.00. Please help, this is urgent.

Code:
```function moneyFormat(amount) {
var	fixValue = parseFloat(Math.pow(10,2));//2 = number of dec places.
var	retValue = parseInt(Math.round(amount * fixValue)) / fixValue;
var result=((parseFloat(amount)*100))/100;
amount=result;

pounds=parseInt(amount);
pence=amount-pounds;
if ((pence > 0.90) && (pence < 0.91)) {
amount=pounds+0.90;
}
if (pounds==amount) {
return amount+".00";
} else if (parseInt(amount*10)==amount*10) {
return amount+"0";
} else {
return (parseFloat((Math.ceil(amount*100))/100));
}
}```

2. Have you tried toFixed?

Also this page has more information on number formatting than you will ever need.

http://www.merlyn.demon.co.uk/js-round.htm

3. toFixed() doesn't return the same values for floating point numbers in different browsers-
IE truncates, but Mozilla rounds the last digit,
and I forget what Opera and Safari do.

If you want to get the same value in all browsers you
can explicitly tell the script to round or trim to the last significant digit:

Code:
```	Number.prototype.fixTrim= function(n){
var N= this;
N= Math.floor(N*Math.pow(10,n));
N/=Math.pow(10,n);
return(N.toFixed(n));
}
Number.prototype.fixRound= function(n){
var N= this;
N= Math.round(N*Math.pow(10,n));
N/=Math.pow(10,n);
return(N.toFixed(n));
}```

4. Originally Posted by mrhoo
toFixed() doesn't return the same values for floating point numbers in different browsers-
IE truncates, but Mozilla rounds the last digit,
Actually, this is a bug in Internet Explorer that numbers in range 0.5 - 0.95 are truncated. eg. (0.6).toFixed(0) gives 0. This can be corrected by setting integer part to not-null, e.g.
Code:
`fixed = ((i + 1).toFixed(2) - 1).toFixed(2);`

5. num.toFixed(0) should be written parseInt((num)).
or to round it to an integer: Math.round(num)

If I want to round 1.19999 to 2 significant digits
I want 1.20, which is 'closer' than 1.19 to the actual floating point value.

6. Originally Posted by mrhoo
num.toFixed(0) should be written parseInt(num).
ECMA standard says toFixed returns a number rounded to the given precision. So, (1.8).toFixed(0) should (and does) return 2, whereas parseInt(1.8) returns 1.

7. So, (1.8).toFixed(0) should (and does) return 2
Yes, but (.8).toFixed(0) returns 0 in IE and 1 in others.

if you want the integer part of a number use parseInt(num),
if you want a rounded whole number use Math.round(num).
Use toFixed(n) if you actually want significant digits.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•