Jason Bourne Jason Bourne - 1 year ago 105
Javascript Question

Javascript: Most Efficient way to convert string to integer then back to string

I have a text input field which has a value of text to take in a string like "$2,000." In my functionality, I need to convert this back to a a number to run some mathematical functions and then spit it out back as another dollar value, which will be formatted like "$2,500.56" (I.E. not "$2,500.567"). Here's the two tests I've run so far:

var amount = "$2,000.58"
// "2000.58"
var amount_no_sym = amount.replace(/[^\d\.]/g, '');
var amount_integer = parseFloat(amount_no_sym);
//2000.58 (will cut out any additional decimal places)
var amount_decimals = amount_integer.toFixed(2);
//Final output is "$2,000.58" - the toLocaleString doesn't add back the , here?
var amount_dollar_string = "$" + amount_decimals.toLocaleString();

var amount = "$2,000.58"
// "2000.58"
var amount_no_sym = amount.replace(/[^\d\.]/g, '');
// 2000.58
var amount_integer = parseFloat(amount_no_sym);
//Final output is "$2,000.58"- but sometimes it will be something like "$3,564.345" for certain calculations.
var amount_dollar_string = "$" + amount_integer.toLocaleString();

Would the most optimal solution be to go to the second one, and then write a function to process a string and cut off the last number after the decimal if there are more than two....? Is there a simpler way and I'm doing too much work?

Thanks in advance!

Answer Source

Don't do your own number formatting. There's an API for that.

var formatter = new Intl.NumberFormat("en-us", { style: "currency", currency: "USD" });

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download