基本的に私の質問は: 130.0 ではなく 130.00000000000003 として値を取得するのはなぜですか?
ボンネットの下にあるすべてを出力しただけで、十分に明確であることを願っています。文字列/フロートが原因である可能性が最も高いことはわかっていますが、解決方法はわかりません。
parseFloat() 、 parseFloat().toFixed(1) 、 parseFloat().round(1) を試しましたが、それでも.00000000000003を取得し続けます。いつもではありませんが、時々。
コード :
// ... 'cost' will be passed as a parameter to the function
totalBudget = parseFloat(document.getElementById('currentBudget').value);// e.g value ='4'
ni = parseFloat(totalBudget);
cost = (cost).toFixed(1);
alert("totalBudget " + totalBudget + "\nni " + ni + "\ncost " + cost);
ni += parseFloat(cost);
alert("ni " + ni);
alert('\nni= ' + ni + '\ntotalBudget= ' + totalBudget + '\ncost=' + cost);
var playerCost = parseFloat(document.getElementById('playerCost' + vTemp).value);
playerCost = (playerCost).toFixed(1);
alert('playerCost= ' + playerCost);
alert('\nNow will subtract ');
ni -= playerCost;
alert('\nAfter Subtraction');
alert('\nni= ' + ni + '\nplayerCost= ' + playerCost);
alert('-------'+
'\ncurrBudget= '+totalBudget+
'\nnew budget ni= '+ni+
'\nPlayer#:vTemp= '+vTemp+
'\nCurr player cost= '+playerCost+
'\nNew players cost= '+cost +
"\nParseFloat(playerCost)for curr player= "+parseFloat(playerCost));
出力:
// If cost = 7.2 and playerCost= 7.1. Notice all floating values are super fine.
totalBudget 129.8
ni 129.8
cost 7.2
totalBudget 129.8
ni 129.8
cost 7.2
ni= 137
totalBudget= 129.8
cost=7.2
plaerCost= 7.1
Now will subtract
After Subtraction
ni= 129.9
playerCost= 7.1
-------
currBudget= 129.8
new budget ni= 129.9
Player#:vTemp= 8
Curr player cost= 7.1
New players cost= 7.2
ParseFloat(playerCost)for curr player= 7.1
ページを更新せずに、Web サイトで別の操作を行います
出力:
// If cost = 7.3 and playerCost= 7.2. Notice floating points are totally not fine.
totalBudget 129.9
ni 129.9
cost 7.3
ni 137.20000000000002
ni= 137.20000000000002
totalBudget= 129.9
cost=7.3
plaerCost= 7.2
Now will subtract
After Subtraction
ni= 130.00000000000003
playerCost= 7.2
-------
currBudget= 129.9
new budget ni= 130.00000000000003
Player#:vTemp= 8
Curr player cost= 7.2
New players cost= 7.3
ParseFloat(playerCost)for curr player= 7.2
すると「予算オーバーです。選手を変えてください!」と出ます。エラー原因 130.00000000000003 > 130.0