How can a float be right padded with zeros such that
- Number of digits after padding is 7
- Zeros are padded to the right of the decimal point
.
- Numbers with more than 7 digits are truncated from the right
.toFixed(6)
ignores the number of digits before the decimal point .
.
Input
9.123
9.123456
6.12345678
100.1
Output
9.123000
9.123450
6.123456
100.1000 // truncated from the right
How can a float be right padded with zeros such that
- Number of digits after padding is 7
- Zeros are padded to the right of the decimal point
.
- Numbers with more than 7 digits are truncated from the right
.toFixed(6)
ignores the number of digits before the decimal point .
.
Input
9.123
9.123456
6.12345678
100.1
Output
9.123000
9.123450
6.123456
100.1000 // truncated from the right
Share
Improve this question
asked Nov 25, 2013 at 0:52
NyxynyxNyxynyx
63.7k163 gold badges507 silver badges856 bronze badges
4
-
You could adjust the number you pass to
.toFixed
by the number of digits before the decimal point. – Felix Kling Commented Nov 25, 2013 at 0:57 - Looks not to hard - did you try sth? – jantimon Commented Nov 25, 2013 at 0:57
- What if 100,000,000 ? – user1636522 Commented Nov 25, 2013 at 17:02
-
1
@wared The number is not expected to hit 100,000,000. If it does, I guess an
if
statement will convert it to exponentil form 1.0E8 – Nyxynyx Commented Nov 26, 2013 at 15:51
3 Answers
Reset to default 5n.toFixed(5).substring(0, 7)
It will fail miserably for anything 100000 or greater.
Note that the result is a string :
var n = 9.123 + '';
if (n.length < 8) {
n += new Array(9 - n.length).join('0');
} else if (n.length > 8) {
n = n.slice(0, 8);
}
This is me trying to be clever :
Number.prototype.toTotallyFixed = function(n) {
var s = this.toString(), a = (s + (s.indexOf('.') != -1 ? '' : '.0')).split('.');
return a[0].length > n ? s.slice(0,n) : a[0] + (+('.'+a[1])).toFixed(n - (a[0].length-1)).slice(1);
}
FIDDLE