2016-10-30 47 views
0

問題我有一個函數誰獲取參數作爲字符串 和現在我想使字符串爲浮動(導致其不是一個整數)的問題Javascript/jQuery - 與字符串浮動和.toFixed()

function(costsForThisPlayer){ 
    moneyRemaining += costsForThisPlayer;    
    moneyRemaining2Decimals = parseFloat(moneyRemaining).toFixed(2); 
} 
在我的例子

現在,我costsForThisplayer是 「1.0」

但現在我的moneyRemaining看起來是這樣的:

991.00

是前面我的錢餘下是99

所以我的代碼只附加值的結束nr而不是增加值?!?!?!

有沒有人有想法?

我想

  • 轉換爲浮動
  • ,然後用2位小數

使與toFixed()的moneyRemaining但它doenst工作

編輯:

這是我的全部js代碼

function addGoalkeeperByClickEvent(playerName, id, costsForThisPlayer) { 
$(document).off('click', '.goalKepperRow, .goalkeeperGreyRow').on('click', '.goalKepperRow, .goalkeeperGreyRow', function() { 

    $('#goalkeeperLine div p').first().parent().html("<div id='"+id+"' costsForThisPlayer='"+costsForThisPlayer+"'><img src='https://d34h6ikdffho99.cloudfront.net/uploads/real_team/shirt/1188/shirt-333.svg'><span class='ui-icon ui-icon-circle-close remove' style='top: -69.0833px; left: 34.3167px;'></span><div>".concat(playerName)); 


    console.log("GK wurde mit Row Click entfernt:"); 

    $(this).attr('class', 'goalKepperRow'); 
    GoalKeeperQuantity--; 
    totalPlayersOnField--; 


    moneyRemaining += costsForThisPlayer; 
    moneyRemaining2Decimals = parseFloat(moneyRemaining).toFixed(2);     
    $("#moneyRemaining").html(moneyRemaining2Decimals+" $ (Mio)"); 


    $("#moneyRemaining").html(moneyRemaining2Decimals+" $ (Mio)");  

    console.log("bis hier hin gehts"); 

    $("#field #".concat($(this).attr('id'))).empty(); 
    $("#field #".concat($(this).attr('id'))).parent().html("<p></p>"); 

    $("#players").html(totalPlayersOnField+"/12");  
}); 

};

+0

上parseInt函數()將toFixed沒有任何影響,因爲整數沒有小數點,要麼你應該使用parseFloat,再次申請parseFloat在costsForThisPlayer上,因爲它也被視爲String。 –

+0

@ClainDsilva對不起,我編輯我的第一後,我parseFloat(嘗試過),這是這不是誤會的工作抱歉事情... 所以還有什麼可能是這個問題? – nbg15

回答

1

您需要申請parseFloat上costsForThisPlayer使兩個float類型來執行加法。

function(costsForThisPlayer){ 
     moneyRemaining = parseFloat(moneyRemaining) + parseFloat(costsForThisPlayer); 
     //use moneyRemaining.toFixed(2) on remaining code       
    } 
+0

@Andreas假設moneyRemaining的類型爲float,否則將parseFloat應用於它,我已經使兩種類型的float,看到更新的答案 –

+0

我已經將現在的整個代碼添加到我的第一篇文章中... – nbg15

+0

@Andreas正確的,我看到你的觀點,修正應用於代碼 –

0

確定這是我的代碼現在;)

moneyRemaining += parseFloat(costsForThisPlayer); 
moneyRemaining2Decimals = moneyRemaining.toFixed(2);     
$("#moneyRemaining").html(moneyRemaining2Decimals+" $ (Mio)");