1

I have a a form where a user can make a simple multiplication of two fields. The outcome of the equation is then placed in another input field using jquery.

quantity =         Number($('#quantity').val());
price =            Number($('#price').val());

subtotal = quantity * price;

and

$("input#subtotal").val(subtotal); 

But...The numbers do not add up!!

I'm getting very strange answers with long decimals behind the comma. When running my console:

console.log(subtotal, price+ "x" + quantity + "=" + subtotal);    

it literally states:

--> 1.07 x 1001 = 1071.0700000000002

What is the best solution here?

Matthias
  • 1,884
  • 2
  • 18
  • 35
  • Floating point inaccuracies. – trincot Feb 10 '16 at 22:59
  • all Javascript numbers are floating point – Stephen Thomas Feb 10 '16 at 22:59
  • If you plan to use that as a number (the `var.toFixed(2).replace(/0{0,2}$/, "");` bit), you're going to have an issue with numbers like `1071.0007`. It results in `"1071."`. I recommend something like `Number(var.toFixed(2))`, but don't use `var`. It's a reserved word in JS as far as I know. – Joseph Marikle Feb 10 '16 at 23:23

1 Answers1

0

I've solved this floating point issue by adding:

myvar = myvar.toFixed(2).replace(/0{0,2}$/, "")

which seems to works well for price type calculations.

EDIT:

As Joseph Marikle indicated in the comments, this might lead to issues with numbers like 1071.0007.

myvar = Number(myvar.toFixed(2)) 

therefore looks to be a more elegant solution.

Matthias
  • 1,884
  • 2
  • 18
  • 35
  • You should not put this as an answer but as an edit to your question. As your question was *"What is going on here???"* and not *"how can I get rid of these decimals"* – trincot Feb 10 '16 at 23:02