| Live demo - enter a value - mcFormatNumber( format, value, digits ) - | ||||||
|---|---|---|---|---|---|---|
| Value | Digits | Valid formats | ||||
| Default | fixed | exp | float | comas | ||
| 1003.14 | 2 | 1003.14 | 1003.14 | 1.00e+3 | 1.0e+3 | 1,003.14 |
| 1 | 1003.14 | 1003.1 | 1.0e+3 | 1e+3 | 1,003.1 | |
| 0 | 1003.14 | 1003 | 1e+3 | not supported | 1,003 | |
| 3.14 | 2 | 3.14 | 3.14 | 3.14e+0 | 3.1 | 3.14 |
| 0.00005 | 4 | 0.00005 | 0.0001 | 5.0000e-5 | 0.00005000 | 0.0001 |
| 0.0000005 | 4 | 5e-7 | 0.0000 | 5.0000e-7 | 5.000e-7 | 0.0000 |
For entered numbers, the default conversion is pretty good .. until the result of some division produces 8 (or more) digits of precision - then it is a disaster!
In addition, I strongly dislike software that produces some result and you simply have to accept it.
In use, the user can select the formatting type and number of digits.
var mcFormatNumber = function( format, value, digits ){
var formattedString = value.toString(); // this could be very long
format = format.toLowerCase();
if (format == "fixed" ) formattedString = value.toFixed(digits);
if (format == "exp" ) formattedString = value.toExponential(digits); // forces exponential notation 3.digits e+5
if (format == "float" )
if (digits > 0) formattedString = value.toPrecision(digits); // total number of significant digits
else formattedString = "not supported";
if (format == "comas") {
formattedString = value.toFixed(digits);
if (value > 1000) { // add only one coma
var xx = Math.trunc(value / 1000);
var yy = (value - xx*1000);
var xyz = "000" + yy.toFixed(digits);
var zz = xyz.match(/\d{3}\.\d+/); // force 3 digits
if (zz==null) zz = xyz.match(/\d{3}$/);
formattedString = xx.toFixed(0) + ',' + zz ;
}
}
return formattedString ;
}
|