最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - How to Zero-pad Float Point Numbers in Javascript and with limit on max number of digits - Stack Overflow

programmeradmin2浏览0评论

How can a float be right padded with zeros such that

  1. Number of digits after padding is 7
  2. Zeros are padded to the right of the decimal point .
  3. 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

  1. Number of digits after padding is 7
  2. Zeros are padded to the right of the decimal point .
  3. 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
Add a ment  | 

3 Answers 3

Reset to default 5
n.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

发布评论

评论列表(0)

  1. 暂无评论