2017-02-05 35 views
0

怎么能像的Javascript格式化十进制数树数小数点后

0.00012006 to 0.00012 
0.00004494 to 0.0000449 
0.000000022732 to 0.0000000227 without becoming a number like 2.3e-8 

我想我的数字格式知道我怎么能在一个快速/有效的方式改变这样的数字。
我想知道如何转换这些数字,但如果有人知道如何格式化它,我也想知道。

+0

如何号码'0.100101','0.1100001','1.000001'应转换? – RomanPerekhrest

回答

0

你发现号码的地方,并加上2的toFixed

function three(v) { 
 
    var n = Math.floor(Math.log(v)/Math.LN10); 
 
    return v.toFixed(n < 2 ? 2 - n : 0); 
 
} 
 

 
var n = [0.00012006, 0.00004494, 0.000000022732, 0.100101, 0.1100001, 1.000001, 12000, 10, 1e10]; 
 

 
console.log(n.map(three));

0

使用yourNumber.toFixed(numberOfDigitsAfterDot)这样的:

function format(n) { 
 
    var _n = n; 
 
    // count the position of the first decimal 
 
    var count = 0; 
 
    do { 
 
    n = n * 10; 
 
    count++; 
 
    } while(n < 1); 
 
    return _n.toFixed(count + 2); 
 
} 
 

 

 
var num = 0.000000022732; 
 

 
console.log(format(num));