Home > Article > Web Front-end > How to Convert Currency Strings to Doubles in Javascript?
Converting Currency Strings to Doubles in Javascript
If you have a text box containing a currency string that you need to convert to a double for calculations, here's how you can do it client-side.
To cast a currency string as a double, you must remove all non-digits and periods. Here's an example:
<code class="javascript">var currency = "-,400.50"; var number = Number(currency.replace(/[^0-9.-]+/g,""));</code>
In this example, we use the replace() method to remove all characters that are not digits, periods, or negative signs. The resulting string is then converted to a double using the Number() function.
The final result is a double value that you can use for calculations:
<code class="javascript">// Result: ,400.50 console.log(number);</code>
This technique allows you to seamlessly convert currency strings to doubles without compromising user input.
The above is the detailed content of How to Convert Currency Strings to Doubles in Javascript?. For more information, please follow other related articles on the PHP Chinese website!