Javascript / jQuery - 字符串到Float和.toFixed()的问题

时间:2016-10-30 14:30:27

标签: jquery

我遇到一个以字符串形式获取参数的函数 现在我想将字符串变为浮点数(因为它不是整数)

function(costsForThisPlayer){
    moneyRemaining += costsForThisPlayer;               
    moneyRemaining2Decimals = parseFloat(moneyRemaining).toFixed(2); 
}

在我的例子中,我的costForThisplayer是“1.0”

但现在我的钱剩下看起来像这样:

991.00

在我的钱之前剩下的是99

所以我的代码只将值附加到nr的末尾而不是添加值?!?!?!

有没有人有想法?

我想

  • 转换为浮动
  • 然后使用带有2个小数位的toFixed()进行剩余金额

但它确实有效

编辑:

这是我的整个 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");      
});

};

2 个答案:

答案 0 :(得分:1)

您需要在costsForThisPlayer上应用parseFloat,以使两种类型的Float都能执行添加。

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

答案 1 :(得分:0)

好的,这是我现在的代码;)

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