2

I have the string "722,311.75" and I want to convert it in number 722,311.75 (money format). The following code doesn't work.

var str = "722,311.75";
var nr = parseFloat(str, 10).toFixed(2);
console.log(nr); // Returns 722.00

Any Idea of how I could do this?

Eliza M
  • 107
  • 9
  • 1
    just use `parseFloat(str.replace(/[,]/g, ""));` – Sherali Turdiyev Oct 02 '15 at 11:49
  • 2
    "722,311.75" is not a valid number representation. `parseFloat` will only see the first number (722) and ignore anything after and inculding the comma. Also, thre is no such thing as a "money format" number in JavaScript. The number will be 722311.75, and then you can provide a modified toString function that inserts commas. – Touffy Oct 02 '15 at 11:50
  • Other duplicates: http://stackoverflow.com/questions/4083372/in-javascript-jquery-what-is-the-best-way-to-convert-a-number-with-a-comma-int, and several others. –  Oct 03 '15 at 09:23

1 Answers1

6

Replace , from the string before passing the string to the parseFloat

If the string contains more than one ,, you can use ragex to remove all occurrences of the ,.

The regex /,/ will match the , literal from the string and g the global flag will make the regex to match all possible strings i.e. all the , from string.

var str = "1,722,311.75";
var nr = parseFloat(str.replace(/,/g, ''), 10).toFixed(2);
document.write(nr);

If the string contains only one ,, you can use replace with string to remove , from the string.

var str = "722,311.75";
var nr = parseFloat(str.replace(',', ''), 10).toFixed(2);
document.write(nr);

Note: replace(',', '') will remove only first occurrence of ,. See first code snippet for regex approach that will replace all the occurrences.

Tushar
  • 85,780
  • 21
  • 159
  • 179
  • 1
    edit your first example. it is not valid. there will be issue if `str = "5,722,311.75";` – Sherali Turdiyev Oct 02 '15 at 11:52
  • 1
    @SheraliTurdiyev Right, that's why I've added second option with title `If the string contains more than one ,` – Tushar Oct 02 '15 at 11:54
  • @Magus Thanks for helping improving the answer, but your edit overwrite my changes so have to rollback – Tushar Oct 02 '15 at 11:59
  • I added comment. ok, just suggest dynamic way (without any condition). – Sherali Turdiyev Oct 02 '15 at 11:59
  • @SheraliTurdiyev If OP is sure that there will be only one `,` in string, using string with replace is faster than regex, so added that, if not then only use regex – Tushar Oct 02 '15 at 12:01
  • It is common question(`Convert string to number in money format JavaScript`). `722,311.75` is just example. it may be another price. – Sherali Turdiyev Oct 02 '15 at 12:07
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/91175/discussion-between-tushar-and-sherali-turdiyev). – Tushar Oct 02 '15 at 12:09