The toFixed method returns a string representation of a number in fixed-point notation. The string contains one digit before the significand's decimal point, and must contain fractionDigits digits after it.
Mozilla DOES round. http://developer.mozilla.org/en/docs...Number:toFixed A string representation of number that does not use exponential notation and has exactly digits digits after the decimal place. The number is rounded if necessary, and the fractional part is padded with zeros if necessary so that it has the specified length.
__________________
If this post contains any code, I may or may not have tested it. It's probably just example code, so no getting knickers in a bunch over a typo, OK? If it doesn't have basic error checking in it, such as object detection or checking if objects are null before using them, put that in there. I'm giving examples, not typing up your whole app for you. You run code at your own risk.
Bored? Visit http://www.kaelisspace.com/
The toFixed method returns a string representation of a number in fixed-point notation. The string contains one digit before the significand's decimal point, and must contain fractionDigits digits after it.
Mozilla DOES round.
Isn't there supposed to be a general standard for this? In any case, the IE action is in error because it's neither truncating nor rounding consistently.
If you want to return the integer part of a number
in any browser use Math.floor(number) instead of .toFixed(0);
To get the same value with .toFixed(n) that IE returns (no rounding)
in other clients (which round the last significant digit in a float)
you must truncate the number.
To get a rounded value in IE as well as the others, you must round it
at the significant digit.
Code:
Number.prototype.toFixedTruncate= function(n){
var N= this;
N= Math.floor(N*Math.pow(10,n));
N/=Math.pow(10,n);
return(N.toFixed(n));
}
Number.prototype.toFixedRound= function(n){
var N= this;
N= Math.round(N*Math.pow(10,n));
N/=Math.pow(10,n);
return(N.toFixed(n));
}
var N=1.379,n=2;
var str=N+' Truncated: '+N.toFixedTruncate(n)+'\n'+N+' Rounded: '+N.toFixedRound(n);
alert(str)
The string returned is the same in all browsers:
1.379 Truncated: 1.37
1.379 Rounded: 1.38
The problem is that JScript has a broken implementation of toFixed. In the FAQ I presented an alternative in the form of toDecimals. A problem with it is that it isn't written for the special case of 0 decimals, and as such doesn't remove the decimal point.
However, let me show you the result in comparison: