0

I have the following javascript code with two variables:

eventTotal = eventTotal + parseFloat(currentElement.title).toFixed(2);

deliveryTotal = deliveryTotal + parseFloat(currentElement.title).toFixed(2);

Whenever i add the variables together using:

totalbox.value = "£" + eventTotal + deliveryTotal;

The output is generally something like "£055.0003.99".

Why is this number not formatting properly and how can i achieve this?

MrCode
  • 63,975
  • 10
  • 90
  • 112
user2279981
  • 71
  • 1
  • 6
  • 2
    `toFixed` returns a string, so you're just concatenating strings. Get the total and then call `toFixed` on the result. – Andrew Whitaker Apr 22 '14 at 16:04
  • 1
    Bear in mind [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Liam Apr 22 '14 at 16:06

3 Answers3

4

toFixed returns a string, not a number. So in order to do addition and not concatenation (with +), you'll have to cast the value back to number:

totalbox.value = "£" + (parseFloat(eventTotal) + parseFloat(deliveryTotal)).toFixed(2);

FWIW: Instead you may use prefixed + as sort of a shortcut of parseFloat:

totalbox.value = "£" + (+eventTotal + +deliveryTotal).toFixed(2);
VisioN
  • 143,310
  • 32
  • 282
  • 281
1

Everyone has pointed out the issue, caused by .toFixed() returning a string, but all of those repeated calls to parseFloat(), toFixed() and casting are a code smell.

It would be better to keep all of your variables as numbers and just pass them through a function to format to a human readable currency.

// convert to currency
function currencyFormat(amount){
    return '£' + (amount*1).toFixed(2);
}

// cast to a number in one place
eventTotal =  eventTotal*1;
deliveryTotal = deliveryTotal*1;

// now work with the variables however you need, knowing that you always have numbers

// output currency
totalbox.value = currencyFormat(eventTotal + deliveryTotal);
eventbox.value = currencyFormat(eventTotal);

Now if you need to change the currency symbol or you want to change the decimal separator, or number of decimal places, it's one change in your reusable code. Also, you should use the HTML entity £ instead of using the raw symbol.

MrCode
  • 63,975
  • 10
  • 90
  • 112
0

Get the total and use

toFixed(2);

eventTotal = (eventTotal + parseFloat(currentElement.title)).toFixed(2);

deliveryTotal = (deliveryTotal + parseFloat(currentElement.title)).toFixed(2);
underscore
  • 6,495
  • 6
  • 39
  • 78