Javascript - Regex replace number with HH:MM - javascript

I am trying to replace 4 numbers with a time format. For example if user enters 1234 to be replaced with 12:34
I have found that this regex does this job
let myString = "1234";
myString.replace(/\b(\d{2})(\d{2})/g, '$1:$2')
But now I am trying to figure out how to use this with cases like
94 - this should be replaced with 23 then it does same for time after the colon
01:74 - this should be replaced with 01:59
I have found a regex which does that ^([0-1]?[0-9]|2[0-3]):[0-5][0-9], but I am not able to figure out how to combine this with .replace

You will need to match on the first and second pair of digits and then bound them by their max values. Once you have the bounded values, you can pad the numbers and join them with a colon.
const toTimeString = (value) => {
const
[, hours, minutes] = value.match(/^(\d{2})(\d{2})$/),
hour = `${Math.min(+hours, 24)}`.padStart(2, '0'),
minute = `${Math.min(+minutes, 59)}`.padStart(2, '0');
return `${hour}:${minute}`;
};
console.log(toTimeString('0174')); // 01:59
console.log(toTimeString('3412')); // 24:12
Now, here is a replacer example:
const minPad = (value, min) => `${Math.min(value, min)}`.padStart(2, '0');
const toTimeString = (value) =>
value.replace(/\b(\d{2})(\d{2})\b/g, (match, hours, minutes) =>
`${minPad(hours, 24)}:${minPad(minutes, 59)}`);
console.log(toTimeString('0174 3412')); // 01:59 24:12

There is an overload of replace which takes a function which you can use to do any logic you need, such as:
let myString = "1234";
function formatTime(input){
return input.replace(/\b(\d{2})(\d{2})/, (_,hh,mm) => {
return `${Math.min(hh,24)}:${Math.min(mm,59)}`
})
}
console.log(formatTime("1234"));
console.log(formatTime("3412"));
console.log(formatTime("0174"));

I do not see any good reason to use regex in your case.
Just a simple function will do the job.
function transformTextToHHMMTimeFormat(text) {
const firstNumber = Number(text.slice(0, 2))
const secondNumber = Number(text.slice(2, 4))
const hour = Math.min(firstNumber, 24)
const minute = Math.min(secondNumber, 59)
return `${hour}:${minute}`
}

Related

Javascript NumberFormat ends up with 'NaN' [duplicate]

I have 2,299.00 as a string and I am trying to parse it to a number. I tried using parseFloat, which results in 2. I guess the comma is the problem, but how would I solve this issue the right way? Just remove the comma?
var x = parseFloat("2,299.00")
console.log(x);
Yes remove the commas:
let output = parseFloat("2,299.00".replace(/,/g, ''));
console.log(output);
Removing commas is potentially dangerous because, as others have mentioned in the comments, many locales use a comma to mean something different (like a decimal place).
I don't know where you got your string from, but in some places in the world "2,299.00" = 2.299
The Intl object could have been a nice way to tackle this problem, but somehow they managed to ship the spec with only a Intl.NumberFormat.format() API and no parse counterpart :(
The only way to parse a string with cultural numeric characters in it to a machine recognisable number in any i18n sane way is to use a library that leverages CLDR data to cover off all possible ways of formatting number strings http://cldr.unicode.org/
The two best JS options I've come across for this so far:
https://github.com/google/closure-library/tree/master/closure/goog/i18n
https://github.com/globalizejs/globalize
On modern browsers you can use the built in Intl.NumberFormat to detect the browser's number formatting and normalize the input to match.
function parseNumber(value, locales = navigator.languages) {
const example = Intl.NumberFormat(locales).format('1.1');
const cleanPattern = new RegExp(`[^-+0-9${ example.charAt( 1 ) }]`, 'g');
const cleaned = value.replace(cleanPattern, '');
const normalized = cleaned.replace(example.charAt(1), '.');
return parseFloat(normalized);
}
const corpus = {
'1.123': {
expected: 1.123,
locale: 'en-US'
},
'1,123': {
expected: 1123,
locale: 'en-US'
},
'2.123': {
expected: 2123,
locale: 'fr-FR'
},
'2,123': {
expected: 2.123,
locale: 'fr-FR'
},
}
for (const candidate in corpus) {
const {
locale,
expected
} = corpus[candidate];
const parsed = parseNumber(candidate, locale);
console.log(`${ candidate } in ${ corpus[ candidate ].locale } == ${ expected }? ${ parsed === expected }`);
}
Their's obviously room for some optimization and caching but this works reliably in all languages.
Caveat: This won't work for numbers in scientific notation (like 1e3 for one thousand).
Remove anything that isn't a digit, decimal separator, or minus sign (-) (or optionally, a + if you want to allow a unary + on the number).
If you can assume that . is the decimal separator (it isn't in many parts of the world; keep reading), that might look like this:
function convertToFloat(str) {
let body = str;
let sign = "";
const signMatch = /^\s*(-|\+)/.exec(str);
// Or if you don't want to support unary +:
// const signMatch = /^\s*(-)/.exec(str);
if (signMatch) {
body = str.substring(signMatch.index + 1);
sign = signMatch[1];
}
const updatedBody = str.replace(/[^\d\.]/g, "");
const num = parseFloat(sign + updatedBody);
return num;
}
Live Example (I've added a fractional portion to the number just to show that working):
function convertToFloat(str) {
let body = str;
let sign = "";
const signMatch = /^\s*(-|\+)/.exec(str);
// Or if you don't want to support unary +:
// const signMatch = /^\s*(-)/.exec(str);
if (signMatch) {
body = str.substring(signMatch.index + 1);
sign = signMatch[1];
}
const updatedBody = str.replace(/[^\d\.]/g, "");
const num = parseFloat(sign + updatedBody);
return num;
}
console.log(convertToFloat("2,299.23"));
If you want to support locales where . isn't the decimal separator (there are many), you can detect the decimal separator and use the detected one in your regular expression. Here's an example function for finding the decimal separator:
function findDecimalSeparator() {
const num = 1.2;
if (typeof Intl === "object" && Intl && Intl.NumberFormat) {
// I'm surprised it's this much of a pain and am hoping I'm missing
// something in the API
const formatter = new Intl.NumberFormat();
const parts = formatter.formatToParts(num);
const decimal = parts.find(({ type }) => type === "decimal").value;
return decimal;
}
// Doesn't support `Intl.NumberFormat`, fall back to dodgy means
const str = num.toLocaleString();
const parts = /1(\D+)2/.exec(str);
return parts[1];
}
Then convertToFloat looks like:
const decimal = findDecimalSeparator();
function convertToFloat(str) {
let body = str;
let sign = "";
const signMatch = /^\s*(-|\+)/.exec(str);
// Or if you don't want to support unary +:
// const signMatch = /^\s*(-)/.exec(str);
if (signMatch) {
body = str.substring(signMatch.index + 1);
sign = signMatch[1];
}
const rex = new RegExp(`${escapeRegex(decimal)}|-|\\+|\\D`, "g");
const updatedBody = body.replace(
rex,
(match) => match === decimal ? "." : ""
);
const num = parseFloat(sign + updatedBody);
return num;
}
Live Example:
const decimal = findDecimalSeparator();
function findDecimalSeparator() {
const num = 1.2;
if (typeof Intl === "object" && Intl && Intl.NumberFormat) {
// I'm surprised it's this much of a pain and am hoping I'm missing
// something in the API
const formatter = new Intl.NumberFormat();
const parts = formatter.formatToParts(num);
const decimal = parts.find(({ type }) => type === "decimal").value;
return decimal;
}
// Doesn't support `Intl.NumberFormat`, fall back to dodgy means
const str = num.toLocaleString();
const parts = /1(\D+)2/.exec(str);
return parts[1];
}
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, "\\$&");
}
function convertToFloat(str) {
let body = str;
let sign = "";
const signMatch = /^\s*(-|\+)/.exec(str);
// Or if you don't want to support unary +:
// const signMatch = /^\s*(-)/.exec(str);
if (signMatch) {
body = str.substring(signMatch.index + 1);
sign = signMatch[1];
}
const rex = new RegExp(`${escapeRegex(decimal)}|-|\\+|\\D`, "g");
const updatedBody = body.replace(
rex,
(match) => match === decimal ? "." : ""
);
const num = parseFloat(sign + updatedBody);
return num;
}
function gid(id) {
const element = document.getElementById(id);
if (!element) {
throw new Error(`No element found for ID ${JSON.stringify(id)}`);
}
return element;
}
function onClick(id, handler) {
gid(id).addEventListener("click", handler);
}
onClick("convert", () => {
const str = gid("num").value;
const num = convertToFloat(str);
console.log(`${JSON.stringify(str)} => ${num}`);
});
<div>Enter a number using your locale's grouping and decimal separators, optionally prefaced with a minus sign (<code>-</code>) or plus sign (<code>+</code>):</div>
<input type="text" id="num" value="-123">
<input type="button" id="convert" value="Convert">
Usually you should consider to use input fields which don't allow free text input for numeric values. But there might be cases, when you need to guess the input format. For example 1.234,56 in Germany means 1,234.56 in US. See https://salesforce.stackexchange.com/a/21404 for a list of countries which use comma as decimal.
I use the following function to do a best guess and strip off all non-numeric characters:
function parseNumber(strg) {
var strg = strg || "";
var decimal = '.';
strg = strg.replace(/[^0-9$.,]/g, '');
if(strg.indexOf(',') > strg.indexOf('.')) decimal = ',';
if((strg.match(new RegExp("\\" + decimal,"g")) || []).length > 1) decimal="";
if (decimal != "" && (strg.length - strg.indexOf(decimal) - 1 == 3) && strg.indexOf("0" + decimal)!==0) decimal = "";
strg = strg.replace(new RegExp("[^0-9$" + decimal + "]","g"), "");
strg = strg.replace(',', '.');
return parseFloat(strg);
}
Try it here: https://plnkr.co/edit/9p5Y6H?p=preview
Examples:
1.234,56 € => 1234.56
1,234.56USD => 1234.56
1,234,567€ => 1234567
1.234.567 => 1234567
1,234.567 => 1234.567
1.234 => 1234 // might be wrong - best guess
1,234 => 1234 // might be wrong - best guess
1.2345 => 1.2345
0,123 => 0.123
The function has one weak point: It is not possible to guess the format if you have 1,123 or 1.123 - because depending on the locale format both might be a comma or a thousands-separator. In this special case the function will treat separator as a thousands-separator and return 1123.
It's baffling that they included a toLocaleString but not a parse method. At least toLocaleString without arguments is well supported in IE6+.
For a i18n solution, I came up with this:
First detect the user's locale decimal separator:
var decimalSeparator = 1.1;
decimalSeparator = decimalSeparator.toLocaleString().substring(1, 2);
Then normalize the number if there's more than one decimal separator in the String:
var pattern = "([" + decimalSeparator + "])(?=.*\\1)";separator
var formatted = valor.replace(new RegExp(pattern, "g"), "");
Finally, remove anything that is not a number or a decimal separator:
formatted = formatted.replace(new RegExp("[^0-9" + decimalSeparator + "]", "g"), '');
return Number(formatted.replace(decimalSeparator, "."));
Number("2,299.00".split(',').join('')); // 2299
The split function splits the string into an array using "," as a separator and returns an array.
The join function joins the elements of the array returned from the split function.
The Number() function converts the joined string to a number.
If you want to avoid the problem that David Meister posted and you are sure about the number of decimal places, you can replace all dots and commas and divide by 100, ex.:
var value = "2,299.00";
var amount = parseFloat(value.replace(/"|\,|\./g, ''))/100;
or if you have 3 decimals
var value = "2,299.001";
var amount = parseFloat(value.replace(/"|\,|\./g, ''))/1000;
It's up to you if you want to use parseInt, parseFloat or Number. Also If you want to keep the number of decimal places you can use the function .toFixed(...).
or try this shorter approach:
const myNum = +('2,299.00'.replace(",",""));
If you have several commas use Regex:
const myNum = +('2,022,233,988.55'.replace(/,/g,""));
// -> myNum = 2022233988.55
Here was my case in an array (for similar use case):
To get the sum of this array:
const numbers = ["11", "7", "15/25", "18/5", "12", "16/25"]
By using parseFloat I would lose the decimals so to get the exact sum I had to first replace the forward slash with dot, then convert the strings to actual numbers.
So:
const currectNumbers = numbers.map(num => +(num.replace("/",".")))
// or the longer approach:
const currectNumbers = numbers
.map(num => num.replace("/","."))
.map(num => parseFloat(num));
This will give me the desired array to be used in reduce method:
currectNumbers = [ 11, 7, 15.25, 18.5, 12, 16.25]
All of these answers fail if you have a number in the millions.
3,456,789 would simply return 3456 with the replace method.
The most correct answer for simply removing the commas would have to be.
var number = '3,456,789.12';
number.split(',').join('');
/* number now equips 3456789.12 */
parseFloat(number);
Or simply written.
number = parseFloat(number.split(',').join(''));
This converts a number in whatever locale to normal number.
Works for decimals points too:
function numberFromLocaleString(stringValue, locale){
var parts = Number(1111.11).toLocaleString(locale).replace(/\d+/g,'').split('');
if (stringValue === null)
return null;
if (parts.length==1) {
parts.unshift('');
}
return Number(String(stringValue).replace(new RegExp(parts[0].replace(/\s/g,' '),'g'), '').replace(parts[1],"."));
}
//Use default browser locale
numberFromLocaleString("1,223,333.567") //1223333.567
//Use specific locale
numberFromLocaleString("1 223 333,567", "ru") //1223333.567
const parseLocaleNumber = strNum => {
const decSep = (1.1).toLocaleString().substring(1, 2);
const formatted = strNum
.replace(new RegExp(`([${decSep}])(?=.*\\1)`, 'g'), '')
.replace(new RegExp(`[^0-9${decSep}]`, 'g'), '');
return Number(formatted.replace(decSep, '.'));
};
With this function you will be able to format values in multiple formats like 1.234,56 and 1,234.56, and even with errors like 1.234.56 and 1,234,56
/**
* #param {string} value: value to convert
* #param {bool} coerce: force float return or NaN
*/
function parseFloatFromString(value, coerce) {
value = String(value).trim();
if ('' === value) {
return value;
}
// check if the string can be converted to float as-is
var parsed = parseFloat(value);
if (String(parsed) === value) {
return fixDecimals(parsed, 2);
}
// replace arabic numbers by latin
value = value
// arabic
.replace(/[\u0660-\u0669]/g, function(d) {
return d.charCodeAt(0) - 1632;
})
// persian
.replace(/[\u06F0-\u06F9]/g, function(d) {
return d.charCodeAt(0) - 1776;
});
// remove all non-digit characters
var split = value.split(/[^\dE-]+/);
if (1 === split.length) {
// there's no decimal part
return fixDecimals(parseFloat(value), 2);
}
for (var i = 0; i < split.length; i++) {
if ('' === split[i]) {
return coerce ? fixDecimals(parseFloat(0), 2) : NaN;
}
}
// use the last part as decimal
var decimal = split.pop();
// reconstruct the number using dot as decimal separator
return fixDecimals(parseFloat(split.join('') + '.' + decimal), 2);
}
function fixDecimals(num, precision) {
return (Math.floor(num * 100) / 100).toFixed(precision);
}
parseFloatFromString('1.234,56')
"1234.56"
parseFloatFromString('1,234.56')
"1234.56"
parseFloatFromString('1.234.56')
"1234.56"
parseFloatFromString('1,234,56')
"1234.56"
If you want a l10n answer do it this way. Example uses currency, but you don't need that. Intl library will need to be polyfilled if you have to support older browsers.
var value = "2,299.00";
var currencyId = "USD";
var nf = new Intl.NumberFormat(undefined, {style:'currency', currency: currencyId, minimumFractionDigits: 2});
value = nf.format(value.replace(/,/g, ""));
If you have a small set of locales to support you'd probably be better off by just hardcoding a couple of simple rules:
function parseNumber(str, locale) {
let radix = ',';
if (locale.match(/(en|th)([-_].+)?/)) {
radix = '.';
}
return Number(str
.replace(new RegExp('[^\\d\\' + radix + ']', 'g'), '')
.replace(radix, '.'));
}
Based on many great architects here, I've simplified it a bit.
I prefer to use Intl.NumberFormat(undefined) to make it use the best fit mechanism.
If the user, like me, has a Danish keyboard, but prefer the Mac to be english, this helps:
if (Number.isNaN(normalized)) return Number(value.replace(',', '.'));
If this is used in a form, I found that I should use inputMode="numeric" rather than type="number".
function parseNumber(value, locales = undefined) {
if (typeof value !== 'string') return value;
const example = Intl.NumberFormat(locales).format('1.1');
const normalized = Number(value.replace(example.charAt(1), '.'));
if (Number.isNaN(normalized)) return Number(value.replace(',', '.'));
return normalized;
}
/* test */
const tests = [
{
locale: 'en-US',
candidate: 1.123,
expected: 1.123,
},
{
locale: 'en-US',
candidate: '1.123',
expected: 1.123,
},
{
locale: 'fr-FR',
candidate: '33.123',
expected: 33.123,
},
{
locale: 'fr-FR',
candidate: '33,123',
expected: 33.123,
},
{
locale: 'da-DK',
candidate: '45.123',
expected: 45.123,
},
{
locale: 'da-DK',
candidate: '45,123',
expected: 45.123,
},
{
locale: 'en-US',
candidate: '0.123',
expected: 0.123,
},
{
locale: undefined,
candidate: '0,123',
expected: 0.123,
},
];
tests.forEach(({ locale, candidate, expected }) => {
const parsed = parseNumber(candidate, locale);
console.log(`${candidate} as ${typeof candidate} in ${locale}: ${parsed} === ${expected}? ${parsed === expected}`);
});
use this instead
const price = 1234567.89;
const formattedPrice = price.toLocaleString(); // "1,234,567.89"
to be more specific
const formattedPrice = price.toLocaleString('en-US', {style: 'currency', currency: 'USD'}); // "$1,234,567.89"

How to join strings conditionally without using let in javascript

I have a situation where I'm trying to join the array of strings only if it has a value. I did using let variable, but I wonder can I do this using map. I'm very mindful on the position, so I used in this way.
const [hours, minutes, seconds] =["", "10", ""]
let time = "";
if (hours) {
time += `${hours}h `;
}
if (minutes) {
time += `${minutes}m `;
}
if (seconds) {
time += `${seconds}s`;
}
console.log(time)
Will I be able to do this using map, filter and join?
If you put the hours, minutes, and seconds back into an array, you can make another array for the suffixes, add the suffixes by mapping the values, then filter out the resulting substrings that are 1 character or less (which would indicate that there wasn't a corresponding value).
const suffixes = ['h', 'm', 's'];
const [hours, minutes, seconds] = ["", "10", ""]; // combine this with the next line if you can
const hms = [hours, minutes, seconds];
const time = hms
.map((value, i) => value + suffixes[i])
.filter(substr => substr.length > 1)
.join(' ');
console.log(time)
Here's a nice little snippet
const suffixs = "hms"; // String arrays of single characters can be shortened to this!
const values = ["","10",""];
var string = values
.map((x,i) => x ? x + suffixs[i] : x)
.filter(x => x)
.join(" ");
console.log(string);
// Or if you want to have 0 in place of empty values
var string2 = values
.map((x,i) => (x || "0") + suffixs[i])
.join(" ");
console.log(string2);
Personally, I would create a list of objects, that represents the time.
I prefer this over using two arrays, as it can save some bugs (like changing the order of the data in one list but not in the other one):
const [hours, minutes, seconds] = ["20", "10", ""];
const time = [
{ amount: hours, sign: "h" },
{ amount: minutes, sign: "m" },
{ amount: seconds, sign: "s" },
];
const str = time
.filter((val) => val.amount)
.map((val) => val.amount + val.sign)
.join(" ");
console.log(str);

add leading zero to simple timestamp addition JavaScript function

I am trying to write a javascript function to sum up two timestamp strings, like 00:04:02 and 00:05:43
I have this function which works, but returns a value like: 0:9:45, I'm trying to improve it so there is a leading zero for the minutes section so it looks more like: 0:09:45 but im having trouble doing so and was wondering if anyone could help me:
function sum(date1, date2){
date1 = date1.split(":");
date2 = date2.split(":");
const result = [];
date1.reduceRight((carry,num, index) => {
const max = [24,60,60][index];
const add = +date2[index];
result.unshift( (+num+add+carry) % max );
return Math.floor( (+num + add + carry) / max );
},0);
return result.join(":");
}
console.log(sum('00:05:43', '00:04:02'))
Pad each digit?
return result.map(r => String(r).padStart(2, "0")).join(":");
If you use the built-in Date methods, you don't need to parse times or do math yourself.
'use strict';
function sumTimestamps(a, b) {
const [A, B] = [a, b].map((x) => new Date('1970-01-01T' + x + '.000Z'));
return new Date(A.getTime() + B.getTime()).toUTCString().split(' ')[4];
}
const sum = sumTimestamps('00:04:02', '00:05:43');
console.log(sum);
// => 00:09:45

How to convert Persian and Arabic digits of a string to English using JavaScript?

How can I convert Persian/Arabic numbers to English numbers with a simple function?
arabicNumbers = ["١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩", "٠"]
persianNumbers = ["۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹", "۰"]
It is the same schema, but the code pages are different.
Oneliner of all 6 possible translations between English, Arabic, and persian Digits.
Caution!! Please note that this solution is not efficient and therefore is not recommended for production code. It is only good as a oneliner. In these methods the '۰۱۲۳۴۵۶۷۸۹' string is created every time for every digit! It is much wiser to create the string once and store it in a variable and use that variable instead. Also, most likely a simple for-loop is much faster!
const e2p = s => s.replace(/\d/g, d => '۰۱۲۳۴۵۶۷۸۹'[d])
const e2a = s => s.replace(/\d/g, d => '٠١٢٣٤٥٦٧٨٩'[d])
const p2e = s => s.replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d))
const a2e = s => s.replace(/[٠-٩]/g, d => '٠١٢٣٤٥٦٧٨٩'.indexOf(d))
const p2a = s => s.replace(/[۰-۹]/g, d => '٠١٢٣٤٥٦٧٨٩'['۰۱۲۳۴۵۶۷۸۹'.indexOf(d)])
const a2p = s => s.replace(/[٠-٩]/g, d => '۰۱۲۳۴۵۶۷۸۹'['٠١٢٣٤٥٦٧٨٩'.indexOf(d)])
e2p("asdf1234") // asdf۱۲۳۴
e2a("asdf1234") // asdf١٢٣٤
p2e("asdf۱۲۳۴") // asdf1234
a2e("asdf١٢٣٤") // asdf1234
p2a("asdf۱۲۳۴") // asdf١٢٣٤
a2p("asdf١٢٣٤") // asdf۱۲۳۴
Explaination:
(s => f(s))(x) is a lambda function that is immediately executed, and will be equal to f(x)
s.replace(pattern, function) looks for matches of pattern in s, for every match m it will replace m with function(m) in the string.
/\d/g is a regex pattern, \d means a digit in the English language, g means global. If you don't specify the g it will only match the first occurrence, otherwise it will match all the occurrences.
In this case for every English digit d in the string, that digit will be replaced by '۰۱۲۳۴۵۶۷۸۹'[d] so, 3 will be replaced by the third index in that list('۰۱۲۳۴۵۶۷۸۹') which is '۳'
/[۰-۹]/g is the equivalent regex for Persian digits this time we can't use the same method, before we took advantage of the fact that javascript is dynamically typed and that d is automatically converted from a string(regex match) to a number(array index) (you can do '1234'['1'] in javascript which is the same as '1234'[1])
but this time we can't do that because '1234'['۱'] is invalid. so we use a trick here and use indexOf which is a function that tells us the index of an element in an array(here a character in a string) so, '۰۱۲۳۴۵۶۷۸۹'.indexOf(۳) will give us 3 because '۳' is the third index in the string '۰۱۲۳۴۵۶۷۸۹'
Use this simple function to convert your string
var
persianNumbers = [/۰/g, /۱/g, /۲/g, /۳/g, /۴/g, /۵/g, /۶/g, /۷/g, /۸/g, /۹/g],
arabicNumbers = [/٠/g, /١/g, /٢/g, /٣/g, /٤/g, /٥/g, /٦/g, /٧/g, /٨/g, /٩/g],
fixNumbers = function (str)
{
if(typeof str === 'string')
{
for(var i=0; i<10; i++)
{
str = str.replace(persianNumbers[i], i).replace(arabicNumbers[i], i);
}
}
return str;
};
Be careful, in this code the persian numbers codepage are different with the arabian numbers.
Example
var mystr = 'Sample text ۱۱۱۵۱ and ٢٨٢٢';
mystr = fixNumbers(mystr);
Refrence
this is a simple way to do that:
function toEnglishDigits(str) {
// convert persian digits [۰۱۲۳۴۵۶۷۸۹]
var e = '۰'.charCodeAt(0);
str = str.replace(/[۰-۹]/g, function(t) {
return t.charCodeAt(0) - e;
});
// convert arabic indic digits [٠١٢٣٤٥٦٧٨٩]
e = '٠'.charCodeAt(0);
str = str.replace(/[٠-٩]/g, function(t) {
return t.charCodeAt(0) - e;
});
return str;
}
an example:
console.log(toEnglishDigits("abc[0123456789][٠١٢٣٤٥٦٧٨٩][۰۱۲۳۴۵۶۷۸۹]"));
// expected result => abc[0123456789][0123456789][0123456789]
best way to do that return index of number in array:
String.prototype.toEnglishDigits = function () {
return this.replace(/[۰-۹]/g, function (chr) {
var persian = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
return persian.indexOf(chr);
});
};
The most High Performance (Fast & Accurate) function that can support both Persian/Arabic digits (Unicode numeral characters) is this:
function toEnDigit(s) {
return s.replace(/[\u0660-\u0669\u06f0-\u06f9]/g, // Detect all Persian/Arabic Digit in range of their Unicode with a global RegEx character set
function(a) { return a.charCodeAt(0) & 0xf } // Remove the Unicode base(2) range that not match
)
}
sample='English: 0123456789 - Persian: ۰۱۲۳۴۵۶۷۸۹ - Arabic: ٠١٢٣٤٥٦٧٨٩';
// English: 0123456789 - Persian: 0123456789 - Arabic: 0123456789
console.log( toEnDigit(sample) );
How it work
First by using replace() + RegEx Character Set in range of Arabic Digit Unicode U+0660 - U+0669 = ٠ ... ۹ & Persian Digit Unicode U+06F0 - U+06F9 = ۰ ... ۹ it will detect any character of the string that match it.
Then because Basic Latin Digits (ASCII) have same ends in Unicode U+0030 - U+0039=0-9, So if we remove the difference of them in base, the end can be same.
For that we can use Bitwise AND (&) operation between their Char-code by using charCodeAt() to just the same part stay.
Explain:
// x86 (Base 10) --> Binary (Base 2)
'٤'.charCodeAt(0); // 1636 (Base 10)
'۴'.charCodeAt(0); // 1780 (Base 10)
(1636).toString(2); // 0000000000000000000001100110 0100 (Base 2)
(1780).toString(2); // 0000000000000000000001101111 0100 (Base 2)
(4).toString(2); // 0000000000000000000000000000 0100 (Base 2)
// We need a // 0000000000000000000000000000 1111 (Base 2)
// To And it, for keeping just the 1's
// 0xf = 15
(15).toString(2); // 0000000000000000000000000000 1111 (Base 2)
// So
(
1780 // 0000000000000000000001101111 0100 (Base 2)
& // AND (Operation)
15 // 0000000000000000000000000000 1111 (Base 2)
)
==
4 // 0000000000000000000000000000 0100 (Base 2)
// ---> true
// Also (1636 & 15) == 4 <--- true
Minified version (All Browsers):
function toEnDigit(s){return s.replace(/[\u0660-\u0669\u06f0-\u06f9]/g,function(a){return a.charCodeAt(0)&15})}
OneLiner (Modern Browsers)
const toEnDigit=s=>s.replace(/[٠-٩۰-۹]/g,a=>a.charCodeAt(0)&15);
If the string may contain both "Arabic" and "Persian" numbers then a one-line "replace" can do the job as follows.
The Arabic and Persian numbers are converted to English equivalents. Other text remains unchanged.
Num= "۳٣۶٦۵any٥۵٤۶32٠۰"; // Output should be "33665any55453200"
Num = Num.replace(/[٠-٩]/g, d => "٠١٢٣٤٥٦٧٨٩".indexOf(d)).replace(/[۰-۹]/g, d => "۰۱۲۳۴۵۶۷۸۹".indexOf(d));
console.log(Num);
Short and easy!
"۰۱۲۳۴۵۶۷۸۹".replace(/([۰-۹])/g, function(token) { return String.fromCharCode(token.charCodeAt(0) - 1728); });
Or in a more modern manner
"۰۱۲۳۴۵۶۷۸۹".replace(/([۰-۹])/g, token => String.fromCharCode(token.charCodeAt(0) - 1728));
You could do something like this that uses the index of the number within the string to do the conversion:
// Returns -1 if `fromNum` is not a numeric character
function convertNumber(fromNum) {
var persianNums = '۰١۲۳۴۵۶۷۸۹';
return persianNums.indexOf(fromNum);
}
var testNum = '۴';
alert("number is: " + convertNumber(testNum));
Or map using a object like this:
// Returns -1 if `fromNum` is not a numeric character
function convertNumber(fromNum) {
var result;
var arabicMap = {
'٩': 9,
'٨': 8,
'٧': 7,
'٦': 6,
'٥': 5,
'٤': 4,
'٣': 3,
'٢': 2,
'١': 1,
'٠': 0
};
result = arabicMap[fromNum];
if (result === undefined) {
result = -1;
}
return result;
}
var testNum = '٤';
alert("number is: " + convertNumber(testNum));
Transforms any Persian or Arabic (or mixed) number to "English" numbers (Hindu–Arabic numerals)
var transformNumbers = (function(){
var numerals = {
persian : ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
arabic : ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
};
function fromEnglish(str, lang){
var i, len = str.length, result = "";
for( i = 0; i < len; i++ )
result += numerals[lang][str[i]];
return result;
}
return {
toNormal : function(str){
var num, i, len = str.length, result = "";
for( i = 0; i < len; i++ ){
num = numerals["persian"].indexOf(str[i]);
num = num != -1 ? num : numerals["arabic"].indexOf(str[i]);
if( num == -1 ) num = str[i];
result += num;
}
return result;
},
toPersian : function(str, lang){
return fromEnglish(str, "persian");
},
toArabic : function(str){
return fromEnglish(str, "arabic");
}
}
})();
//////// ON INPUT EVENT //////////////
document.querySelectorAll('input')[0].addEventListener('input', onInput_Normal);
document.querySelectorAll('input')[1].addEventListener('input', onInput_Arabic);
function onInput_Arabic(){
var _n = transformNumbers.toArabic(this.value);
console.clear();
console.log( _n )
}
function onInput_Normal(){
var _n = transformNumbers.toNormal(this.value);
console.clear();
console.log( _n )
}
input{ width:90%; margin-bottom:1em; font-size:1.5em; padding:5px; }
<input placeholder="write in Arabic numerals">
<input placeholder="write in normal numerals">
function toEnglishDigits(str) {
const persianNumbers = ["۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹", "۰"]
const arabicNumbers = ["١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩", "٠"]
const englishNumbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
return str.split("").map(c => englishNumbers[persianNumbers.indexOf(c)] ||
englishNumbers[arabicNumbers.indexOf(c)] || c).join("")
}
toEnglishDigits("۶٦۵any٥32") // "665any532"
You can use the new Persian-tools library which is an awesome javascript library to deal with Persian words and numbers. Here is a sample for the task you asked for it:
import { digitsArToFa, digitsArToEn, digitsEnToFa, digitsFaToEn } from "persian-tools2";
digitsArToFa("٠١٢٣٤٥٦٧٨٩"); // "۰۱۲۳۴۵۶۷۸۹"
digitsArToEn("٠١٢٣٤٥٦٧٨٩"); // "0123456789"
digitsEnToFa("123۴۵۶"); // "۱۲۳۴۵۶"
digitsFaToEn("۰۱۲۳۴۵۶۷۸۹"); // "0123456789"
You can also find many other useful functionalities on the repository page of the library.
Based on MMMahdy-PAPION method, a short one-line to convert both Persian and Arabic numbers to English numbers and keep all other characters unchanged is the following:
const toEnDigit=n=>n.replace(/[٠-٩۰-۹]/g,n=>15&n.charCodeAt(0));
const toEnDigit=n=>n.replace(/[٠-٩۰-۹]/g,n=>15&n.charCodeAt(0));
sample='English: 0123456789 - Persian (فارسی): ۰۱۲۳۴۵۶۷۸۹ - Arabic (عربي): ٠١٢٣٤٥٦٧٨٩';
// English: 0123456789 - Persian: 0123456789 - Arabic: 0123456789
console.log(toEnDigit(sample) );
For React solution using typescript this might be useful:
// https://gist.github.com/alieslamifard/364862613408a98139da3cab40abbeb9
import React, { InputHTMLAttributes, useEffect, useRef } from 'react';
// Persian/Arabic To English Digit
const f2e = (event) => {
event.target.value = event.target.value
.replace(/[٠-٩]/g, (d) => '٠١٢٣٤٥٦٧٨٩'.indexOf(d))
.replace(/[۰-۹]/g, (d) => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d));
return event;
};
const useForwardedRef = (ref) => {
const innerRef = useRef(null);
useEffect(() => {
if (!ref) return;
if (typeof ref === 'function') {
ref(innerRef.current);
} else {
ref.current = innerRef.current;
}
}, [ref]);
return innerRef;
};
const Input = React.forwardRef<HTMLInputElement, InputHTMLAttributes<HTMLInputElement>>(
(props, ref) => {
const innerRef = useForwardedRef(ref);
useEffect(() => {
innerRef.current?.addEventListener('keyup', f2e);
return () => {
innerRef.current?.removeEventListener('keyup', f2e);
};
}, [innerRef]);
return <input {...props} ref={innerRef} />;
},
);
export default Input;
Simply use Input instead of native input in your form :)
const convertToPersianDigits = (number) => number.toLocaleString('fa-IR')
convertToPersianDigits(100000) //۱۰۰٬۰۰۰
If you have your number string (a string representing a number) at hand, here is a function called paserNumber that converts that into an actual JS Number object:
function parseNumber(numberText: string) {
return Number(
// Convert Persian (and Arabic) digits to Latin digits
normalizeDigits(numberText)
// Convert Persian/Arabic decimal separator to English decimal separator (dot)
.replace(/٫/g, ".")
// Remove other characters such as thousands separators
.replace(/[^\d.]/g, "")
);
}
const persianDigitsRegex = [/۰/g, /۱/g, /۲/g, /۳/g, /۴/g, /۵/g, /۶/g, /۷/g, /۸/g, /۹/g];
const arabicDigitsRegex = [/٠/g, /١/g, /٢/g, /٣/g, /٤/g, /٥/g, /٦/g, /٧/g, /٨/g, /٩/g];
function normalizeDigits(text: string) {
for (let i = 0; i < 10; i++) {
text = text
.replace(persianDigitsRegex[i], i.toString())
.replace(arabicDigitsRegex[i], i.toString());
}
return text;
}
Note that the parse function is quite forgiving and the number string can be a combination of Persian/Arabic/Latin numerals and separators.
After getting a Number you can format it however you want with Number.toLocaleString function:
let numberString = "۱۲۳۴.5678";
let number = parseNumber(numberString);
val formatted1 = number.toLocaleString("fa"); // OR "fa-IR" for IRAN
val formatted2 = number.toLocaleString("en"); // OR "en-US" for USA
val formatted3 = number.toLocaleString("ar-EG"); // OR "ar" which uses western numerals
For more information about formatting numbers, refer to this answer.

How can I parse a string with a comma thousand separator to a number?

I have 2,299.00 as a string and I am trying to parse it to a number. I tried using parseFloat, which results in 2. I guess the comma is the problem, but how would I solve this issue the right way? Just remove the comma?
var x = parseFloat("2,299.00")
console.log(x);
Yes remove the commas:
let output = parseFloat("2,299.00".replace(/,/g, ''));
console.log(output);
Removing commas is potentially dangerous because, as others have mentioned in the comments, many locales use a comma to mean something different (like a decimal place).
I don't know where you got your string from, but in some places in the world "2,299.00" = 2.299
The Intl object could have been a nice way to tackle this problem, but somehow they managed to ship the spec with only a Intl.NumberFormat.format() API and no parse counterpart :(
The only way to parse a string with cultural numeric characters in it to a machine recognisable number in any i18n sane way is to use a library that leverages CLDR data to cover off all possible ways of formatting number strings http://cldr.unicode.org/
The two best JS options I've come across for this so far:
https://github.com/google/closure-library/tree/master/closure/goog/i18n
https://github.com/globalizejs/globalize
On modern browsers you can use the built in Intl.NumberFormat to detect the browser's number formatting and normalize the input to match.
function parseNumber(value, locales = navigator.languages) {
const example = Intl.NumberFormat(locales).format('1.1');
const cleanPattern = new RegExp(`[^-+0-9${ example.charAt( 1 ) }]`, 'g');
const cleaned = value.replace(cleanPattern, '');
const normalized = cleaned.replace(example.charAt(1), '.');
return parseFloat(normalized);
}
const corpus = {
'1.123': {
expected: 1.123,
locale: 'en-US'
},
'1,123': {
expected: 1123,
locale: 'en-US'
},
'2.123': {
expected: 2123,
locale: 'fr-FR'
},
'2,123': {
expected: 2.123,
locale: 'fr-FR'
},
}
for (const candidate in corpus) {
const {
locale,
expected
} = corpus[candidate];
const parsed = parseNumber(candidate, locale);
console.log(`${ candidate } in ${ corpus[ candidate ].locale } == ${ expected }? ${ parsed === expected }`);
}
Their's obviously room for some optimization and caching but this works reliably in all languages.
Caveat: This won't work for numbers in scientific notation (like 1e3 for one thousand).
Remove anything that isn't a digit, decimal separator, or minus sign (-) (or optionally, a + if you want to allow a unary + on the number).
If you can assume that . is the decimal separator (it isn't in many parts of the world; keep reading), that might look like this:
function convertToFloat(str) {
let body = str;
let sign = "";
const signMatch = /^\s*(-|\+)/.exec(str);
// Or if you don't want to support unary +:
// const signMatch = /^\s*(-)/.exec(str);
if (signMatch) {
body = str.substring(signMatch.index + 1);
sign = signMatch[1];
}
const updatedBody = str.replace(/[^\d\.]/g, "");
const num = parseFloat(sign + updatedBody);
return num;
}
Live Example (I've added a fractional portion to the number just to show that working):
function convertToFloat(str) {
let body = str;
let sign = "";
const signMatch = /^\s*(-|\+)/.exec(str);
// Or if you don't want to support unary +:
// const signMatch = /^\s*(-)/.exec(str);
if (signMatch) {
body = str.substring(signMatch.index + 1);
sign = signMatch[1];
}
const updatedBody = str.replace(/[^\d\.]/g, "");
const num = parseFloat(sign + updatedBody);
return num;
}
console.log(convertToFloat("2,299.23"));
If you want to support locales where . isn't the decimal separator (there are many), you can detect the decimal separator and use the detected one in your regular expression. Here's an example function for finding the decimal separator:
function findDecimalSeparator() {
const num = 1.2;
if (typeof Intl === "object" && Intl && Intl.NumberFormat) {
// I'm surprised it's this much of a pain and am hoping I'm missing
// something in the API
const formatter = new Intl.NumberFormat();
const parts = formatter.formatToParts(num);
const decimal = parts.find(({ type }) => type === "decimal").value;
return decimal;
}
// Doesn't support `Intl.NumberFormat`, fall back to dodgy means
const str = num.toLocaleString();
const parts = /1(\D+)2/.exec(str);
return parts[1];
}
Then convertToFloat looks like:
const decimal = findDecimalSeparator();
function convertToFloat(str) {
let body = str;
let sign = "";
const signMatch = /^\s*(-|\+)/.exec(str);
// Or if you don't want to support unary +:
// const signMatch = /^\s*(-)/.exec(str);
if (signMatch) {
body = str.substring(signMatch.index + 1);
sign = signMatch[1];
}
const rex = new RegExp(`${escapeRegex(decimal)}|-|\\+|\\D`, "g");
const updatedBody = body.replace(
rex,
(match) => match === decimal ? "." : ""
);
const num = parseFloat(sign + updatedBody);
return num;
}
Live Example:
const decimal = findDecimalSeparator();
function findDecimalSeparator() {
const num = 1.2;
if (typeof Intl === "object" && Intl && Intl.NumberFormat) {
// I'm surprised it's this much of a pain and am hoping I'm missing
// something in the API
const formatter = new Intl.NumberFormat();
const parts = formatter.formatToParts(num);
const decimal = parts.find(({ type }) => type === "decimal").value;
return decimal;
}
// Doesn't support `Intl.NumberFormat`, fall back to dodgy means
const str = num.toLocaleString();
const parts = /1(\D+)2/.exec(str);
return parts[1];
}
function escapeRegex(string) {
return string.replace(/[/\-\\^$*+?.()|[\]{}]/g, "\\$&");
}
function convertToFloat(str) {
let body = str;
let sign = "";
const signMatch = /^\s*(-|\+)/.exec(str);
// Or if you don't want to support unary +:
// const signMatch = /^\s*(-)/.exec(str);
if (signMatch) {
body = str.substring(signMatch.index + 1);
sign = signMatch[1];
}
const rex = new RegExp(`${escapeRegex(decimal)}|-|\\+|\\D`, "g");
const updatedBody = body.replace(
rex,
(match) => match === decimal ? "." : ""
);
const num = parseFloat(sign + updatedBody);
return num;
}
function gid(id) {
const element = document.getElementById(id);
if (!element) {
throw new Error(`No element found for ID ${JSON.stringify(id)}`);
}
return element;
}
function onClick(id, handler) {
gid(id).addEventListener("click", handler);
}
onClick("convert", () => {
const str = gid("num").value;
const num = convertToFloat(str);
console.log(`${JSON.stringify(str)} => ${num}`);
});
<div>Enter a number using your locale's grouping and decimal separators, optionally prefaced with a minus sign (<code>-</code>) or plus sign (<code>+</code>):</div>
<input type="text" id="num" value="-123">
<input type="button" id="convert" value="Convert">
Usually you should consider to use input fields which don't allow free text input for numeric values. But there might be cases, when you need to guess the input format. For example 1.234,56 in Germany means 1,234.56 in US. See https://salesforce.stackexchange.com/a/21404 for a list of countries which use comma as decimal.
I use the following function to do a best guess and strip off all non-numeric characters:
function parseNumber(strg) {
var strg = strg || "";
var decimal = '.';
strg = strg.replace(/[^0-9$.,]/g, '');
if(strg.indexOf(',') > strg.indexOf('.')) decimal = ',';
if((strg.match(new RegExp("\\" + decimal,"g")) || []).length > 1) decimal="";
if (decimal != "" && (strg.length - strg.indexOf(decimal) - 1 == 3) && strg.indexOf("0" + decimal)!==0) decimal = "";
strg = strg.replace(new RegExp("[^0-9$" + decimal + "]","g"), "");
strg = strg.replace(',', '.');
return parseFloat(strg);
}
Try it here: https://plnkr.co/edit/9p5Y6H?p=preview
Examples:
1.234,56 € => 1234.56
1,234.56USD => 1234.56
1,234,567€ => 1234567
1.234.567 => 1234567
1,234.567 => 1234.567
1.234 => 1234 // might be wrong - best guess
1,234 => 1234 // might be wrong - best guess
1.2345 => 1.2345
0,123 => 0.123
The function has one weak point: It is not possible to guess the format if you have 1,123 or 1.123 - because depending on the locale format both might be a comma or a thousands-separator. In this special case the function will treat separator as a thousands-separator and return 1123.
It's baffling that they included a toLocaleString but not a parse method. At least toLocaleString without arguments is well supported in IE6+.
For a i18n solution, I came up with this:
First detect the user's locale decimal separator:
var decimalSeparator = 1.1;
decimalSeparator = decimalSeparator.toLocaleString().substring(1, 2);
Then normalize the number if there's more than one decimal separator in the String:
var pattern = "([" + decimalSeparator + "])(?=.*\\1)";separator
var formatted = valor.replace(new RegExp(pattern, "g"), "");
Finally, remove anything that is not a number or a decimal separator:
formatted = formatted.replace(new RegExp("[^0-9" + decimalSeparator + "]", "g"), '');
return Number(formatted.replace(decimalSeparator, "."));
Number("2,299.00".split(',').join('')); // 2299
The split function splits the string into an array using "," as a separator and returns an array.
The join function joins the elements of the array returned from the split function.
The Number() function converts the joined string to a number.
If you want to avoid the problem that David Meister posted and you are sure about the number of decimal places, you can replace all dots and commas and divide by 100, ex.:
var value = "2,299.00";
var amount = parseFloat(value.replace(/"|\,|\./g, ''))/100;
or if you have 3 decimals
var value = "2,299.001";
var amount = parseFloat(value.replace(/"|\,|\./g, ''))/1000;
It's up to you if you want to use parseInt, parseFloat or Number. Also If you want to keep the number of decimal places you can use the function .toFixed(...).
or try this shorter approach:
const myNum = +('2,299.00'.replace(",",""));
If you have several commas use Regex:
const myNum = +('2,022,233,988.55'.replace(/,/g,""));
// -> myNum = 2022233988.55
Here was my case in an array (for similar use case):
To get the sum of this array:
const numbers = ["11", "7", "15/25", "18/5", "12", "16/25"]
By using parseFloat I would lose the decimals so to get the exact sum I had to first replace the forward slash with dot, then convert the strings to actual numbers.
So:
const currectNumbers = numbers.map(num => +(num.replace("/",".")))
// or the longer approach:
const currectNumbers = numbers
.map(num => num.replace("/","."))
.map(num => parseFloat(num));
This will give me the desired array to be used in reduce method:
currectNumbers = [ 11, 7, 15.25, 18.5, 12, 16.25]
All of these answers fail if you have a number in the millions.
3,456,789 would simply return 3456 with the replace method.
The most correct answer for simply removing the commas would have to be.
var number = '3,456,789.12';
number.split(',').join('');
/* number now equips 3456789.12 */
parseFloat(number);
Or simply written.
number = parseFloat(number.split(',').join(''));
This converts a number in whatever locale to normal number.
Works for decimals points too:
function numberFromLocaleString(stringValue, locale){
var parts = Number(1111.11).toLocaleString(locale).replace(/\d+/g,'').split('');
if (stringValue === null)
return null;
if (parts.length==1) {
parts.unshift('');
}
return Number(String(stringValue).replace(new RegExp(parts[0].replace(/\s/g,' '),'g'), '').replace(parts[1],"."));
}
//Use default browser locale
numberFromLocaleString("1,223,333.567") //1223333.567
//Use specific locale
numberFromLocaleString("1 223 333,567", "ru") //1223333.567
const parseLocaleNumber = strNum => {
const decSep = (1.1).toLocaleString().substring(1, 2);
const formatted = strNum
.replace(new RegExp(`([${decSep}])(?=.*\\1)`, 'g'), '')
.replace(new RegExp(`[^0-9${decSep}]`, 'g'), '');
return Number(formatted.replace(decSep, '.'));
};
With this function you will be able to format values in multiple formats like 1.234,56 and 1,234.56, and even with errors like 1.234.56 and 1,234,56
/**
* #param {string} value: value to convert
* #param {bool} coerce: force float return or NaN
*/
function parseFloatFromString(value, coerce) {
value = String(value).trim();
if ('' === value) {
return value;
}
// check if the string can be converted to float as-is
var parsed = parseFloat(value);
if (String(parsed) === value) {
return fixDecimals(parsed, 2);
}
// replace arabic numbers by latin
value = value
// arabic
.replace(/[\u0660-\u0669]/g, function(d) {
return d.charCodeAt(0) - 1632;
})
// persian
.replace(/[\u06F0-\u06F9]/g, function(d) {
return d.charCodeAt(0) - 1776;
});
// remove all non-digit characters
var split = value.split(/[^\dE-]+/);
if (1 === split.length) {
// there's no decimal part
return fixDecimals(parseFloat(value), 2);
}
for (var i = 0; i < split.length; i++) {
if ('' === split[i]) {
return coerce ? fixDecimals(parseFloat(0), 2) : NaN;
}
}
// use the last part as decimal
var decimal = split.pop();
// reconstruct the number using dot as decimal separator
return fixDecimals(parseFloat(split.join('') + '.' + decimal), 2);
}
function fixDecimals(num, precision) {
return (Math.floor(num * 100) / 100).toFixed(precision);
}
parseFloatFromString('1.234,56')
"1234.56"
parseFloatFromString('1,234.56')
"1234.56"
parseFloatFromString('1.234.56')
"1234.56"
parseFloatFromString('1,234,56')
"1234.56"
If you want a l10n answer do it this way. Example uses currency, but you don't need that. Intl library will need to be polyfilled if you have to support older browsers.
var value = "2,299.00";
var currencyId = "USD";
var nf = new Intl.NumberFormat(undefined, {style:'currency', currency: currencyId, minimumFractionDigits: 2});
value = nf.format(value.replace(/,/g, ""));
If you have a small set of locales to support you'd probably be better off by just hardcoding a couple of simple rules:
function parseNumber(str, locale) {
let radix = ',';
if (locale.match(/(en|th)([-_].+)?/)) {
radix = '.';
}
return Number(str
.replace(new RegExp('[^\\d\\' + radix + ']', 'g'), '')
.replace(radix, '.'));
}
Based on many great architects here, I've simplified it a bit.
I prefer to use Intl.NumberFormat(undefined) to make it use the best fit mechanism.
If the user, like me, has a Danish keyboard, but prefer the Mac to be english, this helps:
if (Number.isNaN(normalized)) return Number(value.replace(',', '.'));
If this is used in a form, I found that I should use inputMode="numeric" rather than type="number".
function parseNumber(value, locales = undefined) {
if (typeof value !== 'string') return value;
const example = Intl.NumberFormat(locales).format('1.1');
const normalized = Number(value.replace(example.charAt(1), '.'));
if (Number.isNaN(normalized)) return Number(value.replace(',', '.'));
return normalized;
}
/* test */
const tests = [
{
locale: 'en-US',
candidate: 1.123,
expected: 1.123,
},
{
locale: 'en-US',
candidate: '1.123',
expected: 1.123,
},
{
locale: 'fr-FR',
candidate: '33.123',
expected: 33.123,
},
{
locale: 'fr-FR',
candidate: '33,123',
expected: 33.123,
},
{
locale: 'da-DK',
candidate: '45.123',
expected: 45.123,
},
{
locale: 'da-DK',
candidate: '45,123',
expected: 45.123,
},
{
locale: 'en-US',
candidate: '0.123',
expected: 0.123,
},
{
locale: undefined,
candidate: '0,123',
expected: 0.123,
},
];
tests.forEach(({ locale, candidate, expected }) => {
const parsed = parseNumber(candidate, locale);
console.log(`${candidate} as ${typeof candidate} in ${locale}: ${parsed} === ${expected}? ${parsed === expected}`);
});
use this instead
const price = 1234567.89;
const formattedPrice = price.toLocaleString(); // "1,234,567.89"
to be more specific
const formattedPrice = price.toLocaleString('en-US', {style: 'currency', currency: 'USD'}); // "$1,234,567.89"

Categories