0

I am having difficulties with a small math calculation.

I have a string from a form field which I need to convert to a number so I can multiply two fields together (it's a cost and qty field that then sets my total cost line).

The issue I am having is sometimes the number is a solid number (100, 150, 3), sometimes it has commas and sometimes it has decimals.

I have a .replace to replace all the commas with nothing to assist with this issue and it works well.

It works great when I parseInt(var_name) except it strips off my decimal points. I don't want rounding since it's actually part of a purchasing script.

How would I change my two string fields to a numeric field?

var num1 = '100.00';
var num2 = '200,000.51';
alert(num1 X num2); // 20,000,051.00
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
  • If you want floating points, why are you using parseInt? – E.D. May 31 '17 at 19:51
  • It would really be helpful if you could supply all of your code, or all of the relevant code in a way that shows the problems you are having. https://jsfiddle.net/ – Phillip May 31 '17 at 19:51
  • Coerce the value using `Number(var_name)`. – mhodges May 31 '17 at 19:51
  • `Number('100.00') * Number('200000.51')`, the unary `+` operator works as well. `+('100.00') * +('200000.51')`. If you want the trailing zeroes, convert it back to a string with `.toFixed(2)` – mhodges May 31 '17 at 19:54
  • Possible duplicate of [JavaScript: Parse a string to a number?](https://stackoverflow.com/questions/11665884/javascript-parse-a-string-to-a-number) – Heretic Monkey May 31 '17 at 19:55
  • @MikeMcCaughan Parsing !== coercion – mhodges May 31 '17 at 19:57
  • if you strip the commas and parseFloat it the math will be correct: `num1 = parseFloat(num1.replace(/,/g,''))` – maioman May 31 '17 at 19:57
  • @mhodges And...? The OP has a string and wants a number. The linked duplicate provides a number of methods to do so. – Heretic Monkey May 31 '17 at 20:00
  • @MikeMcCaughan So much confusion and misinformation. parsing does not convert a string to a number.. it parses a string for numbers. Telling people to parse when they are really wanting to coerce is just asking for bugs. It's all over the JS community. – mhodges May 31 '17 at 20:04

0 Answers0