-----------------------------------------------------------------------
FAQ Topic - How do I format a Number as a String with
exactly 2 decimal places?
-----------------------------------------------------------------------
When formatting money for example, to format 6.57634 to 6.58, 6.7 to
6.50, and 6 to 6.00?
Rounding of x.xx5 is unreliable, as most numbers are not represented
exactly. See also:
Why does simple decimal arithmetic give strange results? [ref 1]
The statement `n = Math.round(n * 100)/100` converts `n` to a `Number` value
close to a multiple of `0.01`. However, there are some problems.
Converting the number to a string `(n + "")`, does not give
trailing zeroes. Rounding numbers that are very close to `x.5`, for example,
`Math.round(0.49999999999999992)` results `1`.
ECMA-262 3rd Edition introduced `Number.prototype.toFixed`.
There are bugs in JScript 5.8 and below with certain numbers, for example
`0.007.toFixed(2)` incorrectly results `0.00`.
var numberToFixed =
(function() {
return toFixedString;
function toFixedString(n, digits) {
var unsigned = toUnsignedString(Math.abs(n), digits);
return (n < 0 ? "-" : "") + unsigned;
}
function toUnsignedString(m, digits) {
var t, s = Math.round(m * Math.pow(10, digits)) + "",
start, end;
if (/\D/.test(s)) {
return "" + m;
}
s = padLeft(s, 1 + digits, "0");
start = s.substring(0, t = (s.length - digits));
end = s.substring(t);
if(end) {
end = "." + end;
}
return start + end; // avoid "0."
}
/**
* @param {string} input: input value converted to string.
* @param {number} size: desired length of output.
* @param {string} ch: single character to prefix to s.
*/
function padLeft(input, size, ch) {
var s = input + "";
while(s.length < size) {
s = ch + s;
}
return s;
}
})();
// Test results
document.writeln([
"numberToFixed(9e-3, 12) => " + numberToFixed(9e-3, 12),
"numberToFixed(1.255, 2) => " + numberToFixed(1.255, 2),
"numberToFixed(1.355, 2) => " + numberToFixed(1.355, 2),
"numberToFixed(0.1255, 3) => " + numberToFixed(0.1255, 3),
"numberToFixed(0.07, 2) => " + numberToFixed(0.07, 2),
"numberToFixed(0.0000000006, 1) => " + numberToFixed(0.0000000006, 1),
"numberToFixed(0.0000000006, 0) => " + numberToFixed(0.0000000006, 0)
].join("\n"));
<URL:
http://www.merlyn.demon.co.uk/js-round.htm>
<URL:
http://msdn.microsoft.com/en-us/library/sstyff0z%28VS.85%29.aspx>
References:
-----------
[1]
http://jibbering.com/faq/#binaryNumbers
The complete comp.lang.javascript FAQ is at
http://jibbering.com/faq/
--
The sendings of these daily posts are proficiently hosted
by
http://www.pair.com.