Certainly a stupid question, please forgive me. My customer wants decimal numbers to display with five digits. For example: 100.34 or 37.459. I was accomplishing this with val.toPrecision (5);
; however, when my numbers get really small, I stop getting what I want. For example, if my number is 0.000347, it displays 0.00034700. Now, I understand why it's doing this, but what I don't know is how to get it to display 0.0003. Any thoughts?
Asked
Active
Viewed 4,489 times
1

Nik
- 7,113
- 13
- 51
- 80
-
2Check out http://stackoverflow.com/questions/610406/javascript-printf-string-format and the first answer's sprintf link – mrk Jul 08 '11 at 15:14
4 Answers
5
Math.round(0.000347 * 1e4) / 1e4
Or with toFixed
:
Number.prototype.toNDigits = function (n) {
return (Math.abs(this) < 1) ?
this.toFixed(n - 1) :
this.toPrecision(n);
};

katspaugh
- 17,449
- 11
- 66
- 103
2
Our problem is with numbers less than 1 obviously. So catch them and deal them separately
function SetPrecisionToFive(n){
return (n > 1) ? n.toPrecision (5) : (Math.round(n * 1e4) / 1e4).toString();
}

naveen
- 53,448
- 46
- 161
- 251
-1
The Javascript toFixed() function will truncate small numbers to a fixed decimal precision, eg:
var num = .0000350;
var result = num.toFixed(5); // result will equal .00003

Kyle
- 4,202
- 1
- 33
- 41
-
-
@katspaugh this code snippet would be conditional... not meant to cover all cases – Kyle Jul 08 '11 at 15:19