0

I have this code in javascript:

var childrenSize = 7;

    var flAmt = parseFloat(100);
    var amt   = parseFloat(flAmt/childrenSize);

    //Rounding-off fix
    var newAmt = (amt.toFixed(2))*childrenSize;
    alert(newAmt);
    var excess = 0;
    if(newAmt != flAmt)
        excess = parseFloat(flAmt - newAmt);
    amt = parseFloat(amt) + excess.toFixed(2);
    alert(amt);

amt should be 14.25. But instead, it becomes 14.285714285714286-0.03... why?
Also, how can I improve my code?

4
  • 1
    "amt should be 100" Why? You divide 100 by 7. Commented Oct 27, 2014 at 14:52
  • What result are you expecting? jsfiddle.net/5zr7fz0z Commented Oct 27, 2014 at 14:53
  • @j08691 it should be amt should be 14.25 Commented Oct 27, 2014 at 14:57
  • @newbie Did my answer solve your question? Commented Nov 16, 2014 at 7:27

1 Answer 1

2

The toFixed function returns a string, so using the + operator performs a string concatenation instead of an addition.

To get the value of 14.26 which you were (almost) expecting, call toFixed after the addition, like so:

amt = (parseFloat(amt) + excess).toFixed(2);

However, amt is already a float, so is doesn't seem as though parseFloat is needed here.

Sign up to request clarification or add additional context in comments.

2 Comments

Worth noting that you can convert it back to a number by placing a Unary Plus (+) symbol in front of it like so: +(excess.toFixed(2)).
see docs here: toFixed

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.