2017-03-02 42 views
0

如何將該輸出轉換在javascript:小數在JavaScript

A = 1.0000006

B = 0.00005

C = 2.54695621e-7

的輸出:

a = 1

B = 5E-5

C = 2.547e-7

+3

你試過'.toFixed()'和/或'Math.round()'嗎? – nnnnnn

+1

在第一種情況下,使用[* Math.round *](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-math.round),其他人使用[ * toExponential *](http://www.ecma-international.org/ecma-262/7.0/index.html#sec-number.prototype.toexponential)(第二個示例應舍入爲2.547e-7)。 – RobG

+0

@ nnnnnn - 你如何獲得* Math.round *或* toFixed *做科學記數法? – RobG

回答

0

嘗試以下代碼:

var a = 1.0000006; 
 
var b = 0.00005; 
 
var c = 2.54695621e-7; 
 
var a_Result = Math.round(a); 
 
var b_Result = b.toExponential(); 
 
var c_Result = c.toExponential(3); 
 
console.log(a_Result); 
 
console.log(b_Result); 
 
console.log(c_Result);

0

利用該輸入:

var nums = [1.0000006, 0.00005, 2.54695621e-7]; 

可以使用Number#toExponential得到指數形式具有一定精度:

function formatNumber(n) { 
    return n.toExponential(3); 
} 

nums.map(formatNumber) 
// ["1.000e+0", "5.000e-5", "2.547e-7"] 

把它分解成有用的部分:

function formatNumber(n) { 
    return n 
     .toExponential(3) 
     .split(/[.e]/); 
} 

nums.map(formatNumber) 
// [["1", "000", "+0"], ["5", "000", "-5"], ["2", "547", "-7"]] 

並修剪掉多餘的:

function formatNumber(n) { 
    var parts = n 
     .toExponential(3) 
     .split(/[.e]/); 

    var integral = parts[0]; 
    var fractional = '.' + parts[1]; 
    var exponent = 'e' + parts[2]; 

    fractional = fractional.replace(/\.?0+$/, ''); 
    exponent = exponent === 'e+0' ? '' : exponent; 

    return integral + fractional + exponent; 
} 

nums.map(formatNumber) 
// ["1", "5e-5", "2.547e-7"] 

ES6:

const formatNumber = n => { 
    const [, integral, fractional, exponent] = 
     /(\d+)(\.\d+)(e.\d+)/.exec(n.toExponential(3)); 

    return integral + 
     fractional.replace(/\.?0+$/, '') + 
     (exponent === 'e+0' ? '' : exponent); 
};