Home > Web Front-end > JS Tutorial > body text

How to Convert Currency Strings to Doubles in Javascript?

Barbara Streisand
Release: 2024-10-31 17:56:02
Original
114 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!