nbg15 nbg15 - 1 year ago 114
jQuery Question

Javascript / jQuery - Problems with string to Float and .toFixed()

I have a problem with a function who gets a parameter as string
and now i want to make the string to a float (cause its not an integer)

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

in my example now, my costsForThisplayer was "1.0"

but now my moneyRemaining looks like this:


before my moneyRemaining was 99

so my code only appends the value to the end of nr instead of adding the value ?!?!?!

does anyone have an idea?

I thought

  • converting to float

  • and then make the moneyRemaining with toFixed() with 2 decimal places

but it doenst work


This is my whole js code

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');

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");


Answer Source

You need to apply parseFloat on costsForThisPlayer to make both of the type Float to perform an addition.

      moneyRemaining = parseFloat(moneyRemaining) + parseFloat(costsForThisPlayer);
      //use moneyRemaining.toFixed(2) on remaining code                         
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download