I have a list of number like "123,459","561,79" from france region and I want to convert it into our normal US english numbering system. How can I do it in JS using locale?
function eArabic(x){
return x.toLocaleString('en-US',{ minimumFractionDigits:2,
maximumFractionDigits:2 });
}
Input : "123,345"
Output : "123,345"
Expected Output : 123.345
This doesn't looks good. Do you have any suggestion for this problem? I do not want to replace comma with '.' in order to solve this issue.
You’re passing in a string, not a Number object (which is what toLocaleString requires to produce a formatted number). Do you have the original number available?
If you don’t, then your best bet (assuming a standardised format for the original number strings) would be to convert them into normal numbers then reformat them. Assuming that your numbers are going to be formatted according to French standards (, as a decimal separator) then you could use a simple string replacement before creating your number object:
var frenchNumberString = '123,456';
var numberObject = new Number(frenchNumberString.replace(',', '.'));
Then pass numberObject into your formatting code.
Related
In JS, I do have a float number which come from php as below:
var number = 2,206.00
In JS, I need to use parseFloat that number.
So I tried parseFloat(number), but its give only 2. So how can I get 2206.00 instead of 2?
Number.parseFloat is the same function object as globalThis.parseFloat.
If globalThis.parseFloat encounters a character other than:
a plus sign or,
a minus sign or,
a decimal point or,
an exponent (E or e)
...it returns the value up to that character, ignoring the invalid character and characters following it. A second decimal point also stops parsing.
So the following prints 2. And this seems to be your problem.
console.log(parseFloat('2,206.00')) // 2
Solution: use string manipulation to remove any commas from the number (really a String before parsing it.
console.log(parseFloat('2,206.00'.replaceAll(',', ''))) // 2206
If you need to store the value as a number but render it as a formatted string, you may need Number#toFixed to render the values after the decimal point:
console.log((2206).toFixed(2)) // '2206.00'
Final note: be careful about localization because some countries use commas for decimal points and decimal points for number grouping. As #t.niese says: store number values without localization, and then apply localization at the surface of your app. But that is a wider, more complicated topic.
You have to remove comma first and use parseFloat.
And about 2 decimal after dot, I see you use number_format($myNumber, 2) in PHP, so in JS, you use .toFixed(2).
var number = '2,206.00';
var result = parseFloat(number.replace(/,/g, '')).toFixed(2);
console.log(result);
First of all what you currently have most probably would trigger an Unexpected number error in JS.
It seems the generated value comes from the number_format() PHP function which returns a string. Moreover the var number variable should also be considered a string as we have a string format.
So firstly you should quote var number = '2,206.00' after that, you have to make the string float-like in order to parse it as float so we should replace , with empty string in order for the number to become 2206.00 number = number.replace(",",""). Lastly the parse should be done now in order to convert the float-like string to an actual float parseFloat(number).
Whole code:
var number = '2,206.00';
number.replace(",","");
number = parseFloat(number);
ok, basically you want a two decimal number after point like (20.03),
try this
parseFloat(number).toFixed(2)
I have a string below that is a price in £, I want to remove the currency symbol and then convert this into a number/price I can use to compare against another value (eg. X >= Y ...)
£14.50
I have previously converted strings to numbers used for currency with
var priceNum = parseFloat(price);
IDEAL OUTCOME
14.50 as a number value. Can this be done in a single line?
I found this very helpful
var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9\.-]+/g,""));
Convert (Currency) String to Float
If the currency symbol will always be there, just use substring:
var priceNum = parseFloat(price.substring(1));
If it may or may not be there, you could use replace to remove it:
var priceNum = parseFloat(price.replace(/£/g, ""));
Beware that parseFloat("") is 0. If you don't want 0 for an empty input string, you'll need to handle that. This answer has a rundown of the various way to convert strings to numbers in JavaScript and what they do in various situations.
Side note: Using JavaScript's standard numbers for currency information is generally not best practice, because if things like the classic 0.1 + 0.2 issue (the result is 0.30000000000000004, not 0.3). There are various libraries to help, and BigInt is coming to JavaScript as well (it's a Stage 3 proposal at the moment, currently shipping in Chrome). BigInt is useful because you can use multiples of your basic currency (for instance, * 100 for pounds and pence).
try this number-formatter-npm library. This library is fantastic.
npm i number-formatter-npm
documentation:https://www.npmjs.com/package/number-formatter-npm
I have defined an input in HTML that represents a number. I need to parse the string in JavaScript to a number taking into consideration the different languages that will be entered by the user, for example: '1.34' in English will be written as '1,34' in French. parseFloat('1,344') will be return 1 in case we are in English standard.
You could probably find a library for it, but you can also pretty easily format the numbers into the wanted format yourself.
When you get a number from the input just convert it to string and then use the indexOf() function (http://www.w3schools.com/jsref/jsref_indexof.asp) to see if there's a comma or a dot in the number. It returns the position index of that element in a string so you can then replace with the wanted one to format the number. Position will be -1 if there is no dot/comma.
var num = 32.14;
var string = String(num);
var position = string.indexOf(".");
Hope this helps you.
If it's only those two representations you consider, then another easy solution is to always do
var floatNum = num.replace(/,/g,".");
and then just treat it like any float number.
Unless you really need it for other number systems I'd avoid using a library. Libraries tend to be too big for most projects to utilize properly in my opinion.
Hello I have a phone number in it's E164 format : +212640588740 and I want to convert it to it's international format : +212 640-588740.
There is this library http://code.google.com/p/libphonenumber/ that do this conversion very well but it requires a phone number and a country code witch I can't provide because I'm reading the phone to convert from DB.
Basically I want a script or library that takes the E164 as arguments and turns it into it's international standard format, like the following:
+212640588740 => +212 640-588740
+33336578668 => +33 3 36 57 86 68
+17877491410 => +1 787-749-1410
Any Ideas are welcome, Thank you in Advance.
If all your input is E164 formatted, you can use com.google.i18n.phonenumbers.PhoneNumberUtil.parse() method to convert your string to PhoneNumber instance which in turn you could use com.google.i18n.phonenumbers.PhoneNumberUtil.format() to convert it to a string formatted as INTERNATIONAL.
You don't need to know the country code (or parse it) beforehand, see the params documentation of the parse() method:
defaultRegion - ... If the number is guaranteed to start with a '+' followed by the country calling code, then "ZZ" or null can be supplied.
Here's a short example:
PhoneNumber number = com.google.i18n.phonenumbers.PhoneNumberUtil.parse("+12781112222", null);
String result = com.google.i18n.phonenumbers.PhoneNumberUtil.format(number, com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat.INTERNATIONAL);
For usage see the docs:
com.google.i18n.phonenumbers.PhoneNumberUtil.parse()
com.google.i18n.phonenumbers.PhoneNumberUtil.format()
My problem is really simple but I'm not sure if there's a "native" solution using JSON.parse.
I receive this string from an API :
{ "key" : -922271061845347495 }
When I'm using JSON.parse on this string, it turns into this object:
{ "key" : -922271061845347500 }
As you can see, the parsing stops when the number is too long (you can check this behavior here). It has only 15 exact digits, the last one is rounded and those after are set to 0. Is there a "native" solution to keep the exact value ? (it's an ID so I can't round it)
I know I can use regex to solve this problem but I'd prefer to use a "native" method if it exists.
Your assumption that the parsing stops after certain digits is incorrect.
It says here:
In JavaScript all numbers are floating-point numbers. JavaScript uses
the standard 8 byte IEEE floating-point numeric format, which means
the range is from:
±1.7976931348623157 x 10308 - very large, and ±5 x 10-324 - very small.
As JavaScript uses floating-point numbers the accuracy is only assured
for integers between: -9007199254740992 (-253) and 9007199254740992
(253)
You number lies outside the "accurate" range hence it is converted to the nearest representation of the JavaScript number. Any attempt to evaluate this number (using JSON.parse, eval, parseInt) will cause data loss. I therefore recommend that you pass the key as a string. If you do not control the API, file a feature request.
The number is too big to be parsed correctly.
One solution is:
Preprocessing your string from API to convert it into string before parsing.
Preform normal parsing
Optionally, you could convert it back into number for your own purpose.
Here is the RegExp to convert all numbers in your string (proceeded with :) into strings:
// convert all number fields into strings to maintain precision
// : 922271061845347495, => : "922271061845347495",
stringFromApi = stringFromApi.replace(/:\s*(-?\d+),/g, ': "$1",');
Regex explanation:
\s* any number of spaces
-? one or zero '-' symbols (negative number support)
\d+ one or more digits
(...) will be put in the $1 variable