How to convert a currency string to a double with Javascript?

JavascriptJquery

Javascript Problem Overview


I have a text box that will have a currency string in it that I then need to convert that string to a double to perform some operations on it.

"$1,100.00"1100.00

This needs to occur all client side. I have no choice but to leave the currency string as a currency string as input but need to cast/convert it to a double to allow some mathematical operations.

Javascript Solutions


Solution 1 - Javascript

Remove all non dot / digits:

var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9.-]+/g,""));

Solution 2 - Javascript

Use a regex to remove the formating (dollar and comma), and use parseFloat to convert the string to a floating point number.`

var currency = "$1,100.00";
currency.replace(/[$,]+/g,"");
var result = parseFloat(currency) + .05;

Solution 3 - Javascript

accounting.js is the way to go. I used it at a project and had very good experience using it.

accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
accounting.unformat("€ 1.000.000,00", ","); // 1000000

You can find it at GitHub

Solution 4 - Javascript

I know this is an old question but wanted to give an additional option.

The jQuery Globalize gives the ability to parse a culture specific format to a float.

https://github.com/jquery/globalize

Given a string "$13,042.00", and Globalize set to en-US:

Globalize.culture("en-US");

You can parse the float value out like so:

var result = Globalize.parseFloat(Globalize.format("$13,042.00", "c"));

This will give you:

13042.00

And allows you to work with other cultures.

Solution 5 - Javascript

I know this is an old question, but CMS's answer seems to have one tiny little flaw: it only works if currency format uses "." as decimal separator. For example, if you need to work with russian rubles, the string will look like this: "1 000,00 rub."

My solution is far less elegant than CMS's, but it should do the trick.

var currency = "1 000,00 rub."; //it works for US-style currency strings as well
var cur_re = /\D*(\d+|\d.*?\d)(?:\D+(\d{2}))?\D*$/;
var parts = cur_re.exec(currency);
var number = parseFloat(parts[1].replace(/\D/,'')+'.'+(parts[2]?parts[2]:'00'));
console.log(number.toFixed(2));

Assumptions:

  • currency value uses decimal notation
  • there are no digits in the string that are not a part of the currency value
  • currency value contains either 0 or 2 digits in its fractional part *

The regexp can even handle something like "1,999 dollars and 99 cents", though it isn't an intended feature and it should not be relied upon.

Hope this will help someone.

Solution 6 - Javascript

This example run ok

var currency = "$1,123,456.00";
var number = Number(currency.replace(/[^0-9\.]+/g,""));
console.log(number);

Solution 7 - Javascript

// "10.000.500,61 TL" price_to_number => 10000500.61

// "10000500.62" number_to_price => 10.000.500,62

JS FIDDLE: https://jsfiddle.net/Limitlessisa/oxhgd32c/

var price="10.000.500,61 TL";
document.getElementById("demo1").innerHTML = price_to_number(price);

var numberPrice="10000500.62";
document.getElementById("demo2").innerHTML = number_to_price(numberPrice);

function price_to_number(v){
	if(!v){return 0;}
	v=v.split('.').join('');
	v=v.split(',').join('.');
	return Number(v.replace(/[^0-9.]/g, ""));
}

function number_to_price(v){
	if(v==0){return '0,00';}
	v=parseFloat(v);
	v=v.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
	v=v.split('.').join('*').split(',').join('.').split('*').join(',');
	return v;
}

Solution 8 - Javascript

This is my function. Works with all currencies..

function toFloat(num) {
    dotPos = num.indexOf('.');
    commaPos = num.indexOf(',');

    if (dotPos < 0)
        dotPos = 0;

    if (commaPos < 0)
        commaPos = 0;

    if ((dotPos > commaPos) && dotPos)
        sep = dotPos;
    else {
        if ((commaPos > dotPos) && commaPos)
            sep = commaPos;
        else
            sep = false;
    }

    if (sep == false)
        return parseFloat(num.replace(/[^\d]/g, ""));

    return parseFloat(
        num.substr(0, sep).replace(/[^\d]/g, "") + '.' + 
        num.substr(sep+1, num.length).replace(/[^0-9]/, "")
    );

}

Usage : toFloat("$1,100.00") or toFloat("1,100.00$")

Solution 9 - Javascript

You can try this

var str = "$1,112.12";
str = str.replace(",", "");
str = str.replace("$", "");
console.log(parseFloat(str));

Solution 10 - Javascript

For anyone looking for a solution in 2021 you can use Currency.js.

After much research this was the most reliable method I found for production, I didn't have any issues so far. In addition it's very active on Github.

currency(123);      // 123.00
currency(1.23);     // 1.23
currency("1.23")    // 1.23
currency("$12.30")  // 12.30

var value = currency("123.45");
currency(value);    // 123.45

Solution 11 - Javascript

I know you've found a solution to your question, I just wanted to recommend that maybe you look at the following more extensive jQuery plugin for International Number Formats:

International Number Formatter

Solution 12 - Javascript

let thousands_seps = '.';
let decimal_sep = ',';

let sanitizeValue = "R$ 2.530,55".replace(thousands_seps,'')
                         .replace(decimal_sep,'.')
                         .replace(/[^0-9.-]+/, '');

// Converting to float
// Result 2530.55
let stringToFloat = parseFloat(sanitizeValue);


// Formatting for currency: "R$ 2.530,55"
// BRL in this case
let floatTocurrency = Number(stringToFloat).toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'});

// Output
console.log(stringToFloat, floatTocurrency);

Solution 13 - Javascript

jQuery.preferCulture("en-IN");
var price = jQuery.format(39.00, "c");

output is: Rs. 39.00

use jquery.glob.js,
    jQuery.glob.all.js

Solution 14 - Javascript

How about simply

Number(currency.replace(/[^0-9-]+/g,""))/100;

Works with all currencies and locales. replaces all non-numeric chars (you can have €50.000,00 or $50,000.00) input must have 2 decimal places

Solution 15 - Javascript

This worked for me and covers most edge cases :)

function toFloat(num) {
  const cleanStr = String(num).replace(/[^0-9.,]/g, '');
  let dotPos = cleanStr.indexOf('.');
  let commaPos = cleanStr.indexOf(',');

  if (dotPos < 0) dotPos = 0;

  if (commaPos < 0) commaPos = 0;

  const dotSplit = cleanStr.split('.');
  const commaSplit = cleanStr.split(',');

  const isDecimalDot = dotPos
    && (
      (commaPos && dotPos > commaPos)
      || (!commaPos && dotSplit[dotSplit.length - 1].length === 2)
    );

  const isDecimalComma = commaPos
    && (
      (dotPos && dotPos < commaPos)
      || (!dotPos && commaSplit[commaSplit.length - 1].length === 2)
    );

  let integerPart = cleanStr;
  let decimalPart = '0';
  if (isDecimalComma) {
    integerPart = commaSplit[0];
    decimalPart = commaSplit[1];
  }
  if (isDecimalDot) {
    integerPart = dotSplit[0];
    decimalPart = dotSplit[1];
  }

  return parseFloat(
    `${integerPart.replace(/[^0-9]/g, '')}.${decimalPart.replace(/[^0-9]/g, '')}`,
  );
}

toFloat('USD 1,500.00'); // 1500
toFloat('USD 1,500'); // 1500
toFloat('USD 500.00'); // 500
toFloat('USD 500'); // 500

toFloat('EUR 1.500,00'); // 1500
toFloat('EUR 1.500'); // 1500
toFloat('EUR 500,00'); // 500
toFloat('EUR 500'); // 500

Solution 16 - Javascript

Here's a simple function -

function getNumberFromCurrency(currency) {
  return Number(currency.replace(/[$,]/g,''))
}

console.log(getNumberFromCurrency('$1,000,000.99')) // 1000000.99

Solution 17 - Javascript

For currencies that use the ',' separator mentioned by Quethzel Diaz

Currency is in Brazilian.

var currency_br = "R$ 1.343,45";
currency_br = currency_br.replace('.', "").replace(',', '.');
var number_formated = Number(currency_br.replace(/[^0-9.-]+/g,""));

Solution 18 - Javascript

    $ 150.00
    Fr. 150.00
    € 689.00

I have tested for above three currency symbols .You can do it for others also.

    var price = Fr. 150.00;
    var priceFloat = price.replace(/[^\d\.]/g, '');

Above regular expression will remove everything that is not a digit or a period.So You can get the string without currency symbol but in case of " Fr. 150.00 " if you console for output then you will get price as

    console.log('priceFloat : '+priceFloat);

    output will be like  priceFloat : .150.00

which is wrong so you check the index of "." then split that and get the proper result.

    if (priceFloat.indexOf('.') == 0) {
            priceFloat = parseFloat(priceFloat.split('.')[1]);
    }else{
            priceFloat = parseFloat(priceFloat);
    }

Solution 19 - Javascript

function NumberConvertToDecimal (number) {
    if (number == 0) {
       return '0.00'; 
    }
    number = parseFloat(number);
    number = number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1");
    number = number.split('.').join('*').split('*').join('.');
    return number;
}

Solution 20 - Javascript

var parseCurrency = function (e) {
    if (typeof (e) === 'number') return e;
    if (typeof (e) === 'string') {
        var str = e.trim();
        var value = Number(e.replace(/[^0-9.-]+/g, ""));
        return str.startsWith('(') && str.endsWith(')') ? -value: value;
    }

    return e;
} 

Solution 21 - Javascript

This function should work whichever the locale and currency settings :

function getNumPrice(price, decimalpoint) {
    var p = price.split(decimalpoint);
    for (var i=0;i<p.length;i++) p[i] = p[i].replace(/\D/g,'');
    return p.join('.');
}

This assumes you know the decimal point character (in my case the locale is set from PHP, so I get it with <?php echo cms_function_to_get_decimal_point(); ?>).

Solution 22 - Javascript

Such a headache and so less consideration to other cultures for nothing...

here it is folks:

let floatPrice = parseFloat(price.replace(/(,|\.)([0-9]{3})/g,'$2').replace(/(,|\.)/,'.'));

as simple as that.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBobby BorszichView Question on Stackoverflow
Solution 1 - JavascriptChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JavascriptJamieView Answer on Stackoverflow
Solution 3 - JavascriptThomas KremmelView Answer on Stackoverflow
Solution 4 - JavascriptPhillView Answer on Stackoverflow
Solution 5 - JavascriptVindicarView Answer on Stackoverflow
Solution 6 - JavascriptTony NguyenView Answer on Stackoverflow
Solution 7 - JavascriptLimitless isaView Answer on Stackoverflow
Solution 8 - JavascriptbycoderView Answer on Stackoverflow
Solution 9 - JavascriptÓlafur WaageView Answer on Stackoverflow
Solution 10 - JavascriptDiego FortesView Answer on Stackoverflow
Solution 11 - JavascriptIEnumeratorView Answer on Stackoverflow
Solution 12 - JavascriptVictor Hugo Soares FreitasView Answer on Stackoverflow
Solution 13 - JavascriptRajesh Kumar MauryaView Answer on Stackoverflow
Solution 14 - JavascriptLourenco SimoesView Answer on Stackoverflow
Solution 15 - JavascriptSimoView Answer on Stackoverflow
Solution 16 - JavascriptBrian BurnsView Answer on Stackoverflow
Solution 17 - JavascriptCaio FelipeView Answer on Stackoverflow
Solution 18 - JavascriptJyotiranjanView Answer on Stackoverflow
Solution 19 - JavascriptSantosh BharadwajView Answer on Stackoverflow
Solution 20 - JavascriptVladislav KostenkoView Answer on Stackoverflow
Solution 21 - JavascriptSkippy le Grand GourouView Answer on Stackoverflow
Solution 22 - JavascriptMerouane NadirView Answer on Stackoverflow