2015-09-14 19 views
0

我已經搜遍了互聯網,但我還沒找到真正適用於我的解決方案。Math.abs()限制運算量

var tv = Length * Type; 

if (tv < 0) 
    { 
    cForm.voltage.value = "-" + Math.abs(tv) + " V"; 
    } 
else... 

由於某些原因,使用這兩個數字進行的一些計算會出現在小數點後15位左右。我想限制返回的十進制數,並且不允許數字向上或向下取整。在計算器上它只能出現在小數點後三位左右,但是Math.abs()會帶來太多的影響。

.toFixed()對我不起作用,因爲如果數字只有2位小數,它會在最後增加0個零。如果計算出來,我只想顯示到第四位。

+0

請提供演示問題的示例輸入值。 – Dai

+1

'「 - 」+ Math.round(Math.abs(tv)* 100)/ 100 +「V」' –

+0

不知何故,人們總是要求如何總是顯示n個小數點,設法爲您的問題找到解決方案:http:// stackoverflow.com/q/2221167/218196,http://stackoverflow.com/q/1726630/218196 –

回答

2

只是擴展@ goto-0的評論,並帶有正確的小數位數。

var tv = Length * Type; 

if (tv < 0) 
    { 
     cForm.voltage.value = "-" + (Math.round(Math.abs(tv) * 10000)/10000) + " V"; 
    } 
else... 
1

下面是作爲截斷額外小數位的函數的實現。如果你想圍繞輸出,你可以使用Number.toPrecision()

function toFixedDecimals(num, maxDecimals) { 
 
    var multiplier = Math.pow(10, maxDecimals); 
 
    return Math.floor(num * multiplier)/multiplier 
 
} 
 

 
console.log(toFixedDecimals(0.123456789, 4)); 
 
console.log(toFixedDecimals(100, 4)); 
 
console.log(toFixedDecimals(100.12, 4));

0

我敢肯定它不是最有效的方法,但它是相當愚笨 -

  1. 抓住你的結果
  2. 基於十進制把它分解成一個數組指向
  3. 然後將小數部分修整爲兩位數(或者您希望的數量很多)。
  4. CONCAT的碎片重新走到一起

很抱歉的長變量名 - 只是試圖弄清楚發生了什麼事:)

// your starting number - can be whatever you'd like 
    var number = 145.3928523; 
    // convert number to string 
    var number_in_string_form = String(number); 
    // split the number in an array based on the decimal point 
    var result = number_in_string_form.split("."); 
    // this is just to show you what values you end up where in the array 
    var digit = result[0]; 
    var decimal = result[1]; 
    // trim the decimal lenght to whatever you would like 
    // starting at the index 0 , take the next 2 characters 
    decimal = decimal.substr(0, 2); 
    // concat the digit with the decimal - dont forget the decimal point! 
    var finished_value = Number(digit + "." + decimal); 

在這種情況下,finished_value會= 145.39