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.
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 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.
I have
var value = $120,90
var value = $1,209.00
currently I replace the first case with
value = value.replaceAll(",", ".").replaceAll("[^0-9.]*", "");
which gives me that I am looking for: the integer 12090
with the second case I run in a problem however like this. How can I solve this in Javascript?
You may modify you regexp.
value = value.replace(/,/g, ".").replace(/^\D|\.(?!\d*$)/g, "");
First will replace ',' to '.' and the 2nd replace NON-digit symbols in the beginning of the string and all dots EXCEPT the last one with the empty string. Then use parseFloat.
To be sure completely it's better to create a template for data input and don't allow users to enter values in an invalid format.
I cannot see how you can make an algorithm work unless you insist that everyone enters dollars and cents. The only option I can think of is to use locale to determine the number separator.
Could you use the answer from this thread?
How can I remove the decimal part from JavaScript number?
They use Math.floor() (round down), Math.ceil() (round up) or Math.round() (round to nearest integer).
sorry, but i'm not that maths guy, so i do not know how it is really called:
number 12345678901234567890123 could be also stated as 1.2345678901234567890123 * 10^22 (if i'm right and did not miss any decimal...)
consider this javascript:
var number = 12345678901234567890123;
var stringValue = number.toString();
if i do so, it renders the alternative translation (mentioned above). instead i want to render simple, plain, ... 12345678901234567890123
how can this be done?
EDIT:
just to be clear: the number i want to render, does not contain any decimal places. it's just a simple 12345678901234567890123 ... not 12345678901234567890123.123 or anything likewise. and, as i'm with javascript, typeof is number
if you still want to deal with numbers on the order of 10^22 without rounding, then you should use a BigInt class, which implements arbitrary sized numbers. There are several BigInt javascript implementations you can find on the net.