sprintf.js
sprintf.js copied to clipboard
Integer printing error for small numbers
If the number is floating point number and its exponent is in certain range, sprintf prints wrong number.
var a = 9.9999e-7;
console.log(a);
// ==> 9.9999e-7
console.log(sprintf('%d', a));
// ==> 9 (0 expected)
console.log(sprintf('%d', a + 0.0001));
// ==> 0
console.log(sprintf('%d', a.toFixed()));
// ==> 0
console.log(parseInt(a));
// ==> 9
console.log(parseInt(a.toFixed()));
// ==> 0
To fix this, if the type specifier is integer (/bcdiuxX/), arg must first be converted to the fixed point number using toFixed(). toFixed() also does the rounding which is also desired.
sprintf isn't doing the right thing when the toString is printed as exponential. exp <= -7 and exp >= 21 cause this problem