2017-08-26 55 views
0

我試圖將2個字段的輸出值設置爲2位小數。
我試過這樣做:.toFixed(2)但它沒有爲我工作。我試過這樣做:Javascript結束爲2位小數不起作用

calculate = function() { 
     var total = document.getElementById('totaal').value; 
     var btw = document.getElementById('percentage').value; 
     document.getElementById('btw').value = parseInt(total.toFixed(2)) * parseInt(btw.toFixed(2))/100; 
    } 

如果該字段以2位小數(例如:3,45)結尾,它工作正常。
但如果它以0結尾,則它不會顯示爲0。

我想這shoudn't是這個mutch的交易,但我只是想現在半天......

提前致謝!

回答

2

當您使用parseInt()然後你刪除了小數點後得出的數字,試試這樣做:

document.getElementById('btw').value = (parseFloat(total) * parseFloat(btw)/100).toFixed(2); 

parseFloat的字符串轉換(因爲輸入值是字符串有必要)輸入到一個浮動,然後除以100並在結果上呼叫.toFixed(2)

1

您可以使用unary plus +將字符串轉換爲數字。

document.getElementById('btw').value = (+total * +btw/100).toFixed(2); 

如果您使用parseInt,那麼您可能會失去精度。

0

您可以使用parseFloat實現這一

var total =65633; 
 
var btw = 12; 
 

 
console.log(parseFloat((total* btw)/100).toFixed(2))

0

你的問題是,你對字符串運行toFixed()toFixed()僅適用於數字。

你可以然而,做到這一點:

document.getElementById('btw').value = 
     (parseInt(total) * parseInt(btw)/100).toFixed(2) 

這需要兩個數字,並完成了所有的數學。 https://jsfiddle.net/6vtrjmax/

0

確保您在整個操作調用toFixeddocument.getElementById("btw").value = (parseInt(total) * parseInt(btw)/100).toFixed(2);

嘗試運行下面的代碼片段:

它,然後它有兩個尾隨小數

見我的小提琴在這裏轉換爲字符串

calculate = function() { 
 
    var total = document.getElementById("total").value; 
 
    var btw = document.getElementById("percentage").value; 
 
    if (total && btw) { 
 
    document.getElementById("btw").value = 
 
     (parseInt(total) * parseInt(btw)/100).toFixed(2); 
 
    } 
 
};
<input onchange="calculate()" placeholder='total' type="decimal" id="total"> 
 
<input onchange="calculate()" placeholder='percentage' type="decimal" id="percentage"> 
 
<input type="decimal" placeholder='result' id="btw">