convert formatted currency amount to a double value using regex - javascript

I have different currency format that I want to convert into a double value. Example:
1,000,000.00 => 1000000.00
2'345',00 => 2345.00
2'344'334.03 => 1000000.03
I have the following solution which works and is very inefficient.I am trying to figure out some regex way of doing it.
decimalPlace = amount[amount.length - 3];
if (decimalPlace === '.' && amount.indexOf(',') < -1 && amount.indexOf("'") < -1) {
return amount
}
if (decimalPlace === ',' && amount.indexOf("'") < -1) {
value = amount.split('.').join('')
.replace(',', '.')
return value
}
if (decimalPlace === '.' && amount.indexOf(',') > -1) {
value = amount.split(',').join('')
return value
}
if (decimalPlace === ',' && amount.indexOf("'") > -1) {
value = amount.split("'").join('')
.replace(',', '.')
return value
}
if (decimalPlace === '.' && amount.indexOf("'") > -1) {
value = amount.split("'").join('')
return value
}
return amount
I would appreciate any suggestion with this issue.

You've probably made this more complicated then it has to be.
If those are the only formats that need to be supported, you could use a function like this:
var v1 = "1,000,000.00";
var v2 = "2'345',00";
var v3 = "2'344'334.03";
var v4 = "2,00"
function format(str){
if(str.replace(/[^,]/g, "").length === 1){ // Contains only one comma.
str = str.replace(",", ".");
}
if(str.indexOf("'")!=-1){
str = str.replace(/'/g, "").replace(",", ".");
}
return parseFloat(str.replace(/,/g, "")).toFixed(2);
}
[v1, v2, v3, v4].forEach(v => console.log(format(v)));
EDIT: I've added support for values with only one comma.
EDIT 2: Actually, it seems that I've made that mistake myself (making thing complicated).
I think all this can be as simple as:
var v1 = "1,000,000.00";
var v2 = "2'345',00";
var v3 = "2'344'334.03";
var v4 = "2,00"
function format(str){
if(str.replace(/[^,]/g, "").length === 1){ // Contains only one comma.
str = str.replace(",", ".");
}
return parseFloat(str.replace(/[^0-9\.]/g, "")).toFixed(2);
}
[v1, v2, v3, v4].forEach(v => console.log(format(v)));

I'd recommend against relying too much on regular expressions here. The way I'd approach this is in 2 parts.
First, work out what the decimal point is. This will change based on locale but it's very easy to work it out - just create a function which will add a localised decimal point and then return it.
function getDecimalPoint(locale) {
return (1.2).toLocaleString(locale).replace(/\d+/g, "");
}
The benefit of this function is that if you pass in no locale, the current one will be used (which is "en-GB" for me).
Now that you can identify a decimal point, you can use that to split the formatted number into 2 parts - evenything before the decimal (whole numbers) and everything after it (decimals).
function unformatNumber(number, locale) {
// Split the number based on the decimal point.
var numberParts = String(number).split(getDecimalPoint(locale));
// Remove everything that isn't a number from the whole numbers and parse
// it as a number.
var unformatted = Number(numberParts[0].replace(/\D+/g, ""));
// Check to see if there are any decimals. If there are, convert them into
// a decimal and add them to the unformatted result.
var decimals = numberParts[1];
if (decimals && decimals.length) {
unformatted += decimals / Math.pow(10, decimals.length);
}
return unformatted;
}
To use it, simply pass your numbers to the function.
unformatNumber("1,000,000.00"); // -> 1000000
unformatNumber("2'345',00", "fr"); // -> 2345
unformatNumber("2'344'334.03"); // -> 2344344.03
// I know those numbers aren't formatted in French, but you can change your
// format as necessary.
function getDecimalPoint(locale) {
return (1.2).toLocaleString(locale).replace(/\d+/g, "");
}
function unformatNumber(number, locale) {
var numberParts = String(number).split(getDecimalPoint(locale));
var unformatted = Number(numberParts[0].replace(/\D+/g, ""));
var decimals = numberParts[1];
if (decimals && decimals.length) {
unformatted += decimals / Math.pow(10, decimals.length);
}
return unformatted;
}
console.log(unformatNumber("1,000,000.00"));
console.log(unformatNumber("2'345',00", "fr"));
console.log(unformatNumber("2'344'334.03"));

Related

NaN (not a number) when attempting output 2 decimal place for money value [duplicate]

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.
Remove all non dot / digits:
var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9.-]+/g,""));
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
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;
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.
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.
This example run ok
var currency = "$1,123,456.00";
var number = Number(currency.replace(/[^0-9\.]+/g,""));
console.log(number);
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
typescript
import currency from "currency.js";
currency("$12.30").value; // 12.30
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$")
// "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;
}
You can try this
var str = "$1,112.12";
str = str.replace(",", "");
str = str.replace("$", "");
console.log(parseFloat(str));
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);
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
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
jQuery.preferCulture("en-IN");
var price = jQuery.format(39.00, "c");
output is: Rs. 39.00
use jquery.glob.js,
jQuery.glob.all.js
Here's a simple function -
function getNumberFromCurrency(currency) {
return Number(currency.replace(/[$,]/g,''))
}
console.log(getNumberFromCurrency('$1,000,000.99')) // 1000000.99
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,""));
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;
}
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
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.
$ 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);
}
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;
}
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(); ?>).
You should be able to handle this using vanilla JS. The Internationalization API is part of JS core: ECMAScript Internationalization API
https://www.w3.org/International/wiki/JavaScriptInternationalization
This answer worked for me: How to format numbers as currency strings

Move comma position JavaScript

I'm trying to move the position of the comma with the use of JavaScript. I have managed to remove all the parts of the string I needed removing. The only problem is that the comma is in the wrong position.
The current outcome is 425.00, but I simply want '42.50'
success: function(result) {
if (result != '') {
alert(" "+result+" ");
}
var discountVal = result.replace(/\D/g,'');
newDiscountVal = discountVal.replace(7.50, '');
$("input#amount").val(discountVal);
}
I am grabbing database echo values with a combination of string and echo - numbers..
You could divide by ten, then convert back to a String using toFixed(2) which forces formatting of 2 decimal places
Javascript allows implicit conversion of Strings to numbers, by firstly converting the String to a Number so it is valid to divide a String by a number.
var input= "4250.00";
var output = (original / 100).toFixed(2); // => "42.50"
Note this method has different behaviour due to rounding. Consider the case 9.99. If you use a string manipulation technique you'll get ".99", with divide by 10 method above you'll get "1.00". However from what has been said in comments I believe your inputs always end .00 and never anything else, so there will be no difference in reality.
If it is number you can just divide by 10
If it is string you can do like this:
var ind = text.indexOf('.');
text = text.replace('.', '');
text.slice(0, ind-1) + '.' + text.slice(ind-1, text.length)
Here is a solution:
function moveComma(val, moveCommaByInput) {
if (val || typeof val === 'number') {
const valueNumber = Number(val);
const moveCommaBy = moveCommaByInput || 0;
if (isNaN(valueNumber)) {
return null;
} else {
return Number(`${valueNumber}e${moveCommaBy}`);
}
}
return null;
}
This is how i solved it..
var discountVal = result.replace(/\D/g, '');
var newDiscountVal = discountVal.replace(7.50, '');
var lastDigits = newDiscountVal.substr(newDiscountVal.length - 2);
var removedDigits = newDiscountVal.slice(0,newDiscountVal.length - 2);
var discountRealValue = removedDigits + '.' + lastDigits;
$("input#amount").val(discountRealValue);
Cheers

toLocaleString() for IE 8

Below is my JavaScript:
var s = new Number(123456789);
alert(s.toLocaleString("en-US"));
this gives result 123,456,789 in chrome. But IE 8 shows 123,456,789.00. Is there any workaround to restrict the addition of ".00" in IE?
FYI: I have already checked This which gives problem in Chrome and have searched around google with no use.
// Following #RobG's comment I have altered and simplified to find any character that might be used as a decimal point (unless it's the first character)
var s = new Number(123456789);
var s1 = s.toLocaleString();
var p = new Number(Math.floor(s) + 0.1); // similar value but decimal
var p1 = p.toLocaleString();
var index;
var point;
for (index=p1.length-1; index>0; index--) { // find decimal point in dummy
point = p1.charAt(index);
if (point < '0' || point > '9')
break;
}
if (index > 0) {
index = s1.lastIndexOf(point); // find last point in string
if (index > 0)
s1 = s1.slice(0, index); // truncate decimal part
}
alert(s1);
You can test for the decimal separator and remove it and everything thereafter:
// Work out whether decimal separator is . or , for localised numbers
function getDecimalSeparator() {
return /\./.test((1.1).toLocaleString())? '.' : ',';
}
// Round n to an integer and present
function myToLocaleInteger(n) {
var re = new RegExp( '\\' + getDecimalSeparator() + '\\d+$');
return Math.round(n).toLocaleString().replace(re,'');
}
// Test with a number that has decimal places
var n = 12345.99
console.log(n.toLocaleString() + ' : ' + myToLocaleInteger(n)); // 12,345.99 : 12,346
You'll need to change system settings to test thoroughly.
Edit
If you want to change the built–in toLocaleString, try:
// Only modify if toLocaleString adds decimal places
if (/\D/.test((1).toLocaleString())) {
Number.prototype.toLocaleString = (function() {
// Store built-in toLocaleString
var _toLocale = Number.prototype.toLocaleString;
// Work out the decimal separator
var _sep = /\./.test((1.1).toLocaleString())? '.' : ',';
// Regular expression to trim decimal places
var re = new RegExp( '\\' + _sep + '\\d+$');
return function() {
// If number is an integer, call built–in function and trim decimal places
// if they're added
if (parseInt(this) == this) {
return _toLocale.call(this).replace(re,'');
}
// Otherwise, just convert to locale
return _toLocale.call(this);
}
}());
}
This will modify the built–in toLocaleString only if it adds decimal places to integers.

Culture sensitive ParseFloat Function in JavaScript?

Do anyone have suggestion for writing culture sensitive ParseFloat Function in JavaScript, So that when I have a string 100,000.22 in US culture format the parse float function returns 100000.22 whereas if I enter 100.000,22 in Swedish Culture it returns 100000.22 in float?
I've improved mwilcox' function to handle values withous separators.
function parseFloatOpts (str) {
if(typeof str === "number"){
return str;
}
var ar = str.split(/\.|,/);
var value = '';
for (var i in ar) {
if (i>0 && i==ar.length-1) {
value += ".";
}
value +=ar[i];
}
return Number(value);
}
This is a bit rough-and-ready, but it may be sufficient, allowing you to pass in the thousands and decimal separators:
function parseFloatOpts(num, decimal, thousands) {
var bits = num.split(decimal, 2),
ones = bits[0].replace(new RegExp('\\' + thousands, 'g'), '');
ones = parseFloat(ones, 10),
decimal = parseFloat('0.' + bits[1], 10);
return ones + decimal;
}
Examples:
parseFloatOpts("100.000,22", ',', '.'); //100000.22
parseFloatOpts("100,000.22", '.', ','); //100000.22
NB that this doesn't ensure that the thousands separator really does represent thousands, etc., or do lots of other safeguarding that you may wish to do, depending on the importance of the function.
var parse = function(st){
if(st.indexOf(",") === st.length-3){
st = st.replace(".", "").replace(",", ".");
}else{
st = st.replace(",", "");
}
return parseFloat(st, 10)
}
console.log(parse("100,000.22")) // 100000.22
console.log(parse("100.000,22")) // 100000.22
I'm just checking if there is a comma in the 3rd-to-last position. This could be further refined to check if there is a period in the 4th to last position in the case thee is no comma (such as 100.000)
Looking at lonesomday's gave me this thought:
You could also do:
function parse (str)
var ar = str.split(/\.|,/);
return Number(ar[0]+ar[1]+"."+ar[3]);
Here is a rough function. It will assume the last punctuation to indicate decimals, whether it is a comma, period, or any other character you may need to indicate. It then eliminates other punctuations from the whole number. Puts it back together and parses as float.
function normalizeFloat(number, chars) {
var lastIndex = -1;
for(i=0; i < chars.length; i++) {
t = number.lastIndexOf(chars[i]);
if (t > lastIndex) {
lastIndex = t;
}
}
if (lastIndex == -1) {
lastIndex = number.length;
}
var whole = number.substring(0, lastIndex);
var precision = number.substring(lastIndex);
for (i=0; i < chars.length; i++) {
whole = whole.replace(chars[i], '');
precision = precision.replace(chars[i],'.');
}
number = whole + precision;
f = parseFloat(number);
return f;
}
try this:
alert(normalizeFloat('12.345,77', [',','.']).toFixed(2));
alert(normalizeFloat('12,345.77', [',','.']).toFixed(2));
Need your current Group and Decimal Separator from Culture Info.
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function parseFloatOpts(str, groupSeparator, decimalSeparator) {
if (typeof str === "number") {
return str;
}
var value = str.replace(new RegExp(escapeRegExp(groupSeparator), 'g'), "");
value = value.replace(decimalSeparator, ".");
return Number(value);
}
If you really for displaying and/or parsing floats (or dates or currencies or more) in different locales for JavaScript, then my recommendation is the GlobalizeJS (https://github.com/globalizejs/globalize) library.
It's a bit tough to set up at first (at least it was in my experience), but totally recommended for proper management of this matter.

How do I stop parseFloat() from stripping zeroes to right of decimal

I have a function that I'm using to remove unwanted characters (defined as currency symbols) from strings then return the value as a number. When returning the value, I am making the following call:
return parseFloat(x);
The problem I have is that when x == "0.00" I expect to get 0.00 (a float with two decimals) back. What I get instead is simply 0.
I've also tried the following:
return parseFloat(x).toFixed(2);
and still get simply 0 back. Am I missing something? Any help would be greatly appreciated.
Thank you!!
parseFloat() turns a string into a floating point number. This is a binary value, not a decimal representation, so the concept of the number of zeros to the right of the decimal point doesn't even apply; it all depends on how it is formatted back into a string. Regarding toFixed, I'd suggest converting the floating point number to a Number:
new Number(parseFloat(x)).toFixed(2);
this should work:
return parseFloat(x).toFixed(2);
you can test it by running this in firebug:
var x = '0.00';
alert(parseFloat(x).toFixed(2));
simple:
function decimalPlaces(float, length) {
ret = "";
str = float.toString();
array = str.split(".");
if (array.length == 2) {
ret += array[0] + ".";
for (i = 0; i < length; i++) {
if (i >= array[1].length) ret += '0';
else ret += array[1][i];
}
} else if (array.length == 1) {
ret += array[0] + ".";
for (i = 0; i < length; i++) {
ret += '0'
}
}
return ret;
}
console.log(decimalPlaces(3.123, 6));
For future readers, I had this issue as I wanted to parse the onChange value of a textField into a float, so as the user typed I could update my model.
The problem was with the decimal place and values such as 12.120 would be parsed as 12.12 so the user could never enter a value like 12.1201.
The way I solved it was to check to see if the STRING value contained a decimal place and then split the string at that decimal and then count the number of characters after the place and then format the float with that specific number of places.
To illustrate:
const hasDecimal = event.target.value.includes(".");
const decimalValue = (hasDecimal ? event.target.value.split(".") : [event.target.value, ""])[1];
const parsed = parseFloat(event.target.value).toFixed(decimalValue.length);
const value = isNaN(parsed) ? "" : parsed;
onEditValue(value);
Here is dynamic version of floatParser for those who need
function customParseFloat(number){
if(isNaN(parseFloat(number)) === false){
let toFixedLength = 0;
let str = String(number);
// You may add/remove seperator according to your needs
[".", ","].forEach(seperator=>{
let arr = str.split(seperator);
if( arr.length === 2 ){
toFixedLength = arr[1].length;
}
})
return parseFloat(str).toFixed(toFixedLength);
}
return number; // Not a number, so you may throw exception or return number itself
}

Categories