I have some strange example.
If I write this:
parseFloat("12345,987").toLocaleString("slv")
the result would be as expected(slv has comma as decimal separator):
12.345,987
But if I round first to 2 decimals:
parseFloat("12345,987").toFixed(2).toLocaleString("slv")
the result would be always with english separator(dot):
12,345.99
How is that possible?
It should be: 12.345,99
As described in this answer, parseFloat() is meant to be used with decimals only and therefore passing in a string with commas can lead to unexpected results.
For example, I tried parseFloat("12345,987").toLocaleString("slv") in JsFiddle and my browser (UK locale) gave me 12.345, which is different to your result.
One other point to note is that toFixed() returns a string but toLocaleString() operates on numbers. Applying toLocaleString() to a string might also produce unexpected results for a different reason.
Thank you. I have found a solution:
parseFloat("12345,987").toLocaleString("slv", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
This works ok.
"For example, I tried parseFloat("12345,987").toLocaleString("slv")"
"djskinner" - Can you try with: "sl-SI" instead of slv? Does it still doesn't work?
Related
I have a string "215.00".
I want to convert this to a number and when I do parseInt("215.00") it returns 215 as a number. I want it to be as a number 215.00.
To try and do this I did parseFloat("215.00").toFixed(2);, however this also returns a string. I have found many answers on here, but they all convert the number to a string. Does anyone know how to fix this?
Please see my code attempt below:
var number = "215.00";
parseFloat(number).toFixed(2);
I want to get 215.00 as opposed to "215.00"
I will post here this as an Answer, for future purpose.
If you want to represent the zeros on the right hand-side, you need to represent it as a string. Because the numerical value of 215.00 it is in fact 215, therefore it will not keep the two decimal places.
The parseFloat method would work for a number such as "215.01", where it would parse it to the numerical value of 215.01.
I need to parse a json that contains a long number (that was produces in a java servlet). The problem is the long number gets rounded.
When this code is executed:
var s = '{"x":6855337641038665531}';
var obj = JSON.parse(s);
alert (obj.x);
the output is:
6855337641038666000
see an example here: http://jsfiddle.net/huqUh/
why is that, and how can I solve it?
As others have stated, this is because the number is too big. However, you can work around this limitation by sending the number as a string like so:
var s = '{"x":"6855337641038665531"}';
Then instead of using JSON.parse(), you can use a library such as javascript-bignum to work with the number.
It's too big of a number. JavaScript uses double-precision floats for numbers, and they have about 15 digits of precision (in base 10). The highest integer that JavaScript can reliably save is something like 251.
The solution is to use reasonable numbers. There is no real way to handle such large numbers.
The largest number JavaScript can handle without loss of precision is 9007199254740992.
I faced this issue some time ago, I was able to solve using this lib: https://github.com/josdejong/lossless-json
You can check this example:
let text = '{"normal":2.3,"long":123456789012345678901,"big":2.3e+500}';
// JSON.parse will lose some digits and a whole number:
console.log(JSON.stringify(JSON.parse(text)));
// '{"normal":2.3,"long":123456789012345680000,"big":null}' WHOOPS!!!
// LosslessJSON.parse will preserve big numbers:
console.log(LosslessJSON.stringify(LosslessJSON.parse(text)));
// '{"normal":2.3,"long":123456789012345678901,"big":2.3e+500}'
I've got an app that users input coordinates into.
In the DB and most mapping software they use the decimal notation for lat/lng (eg. 123.1234) rather than the older format: 34N 40' 50.12"
I need to test that a value input into a form is a float, and not a string. But using parseFloat on 34N 40' 50.12" returns 34-- which validates using most tests.
Here's what I'm trying, which is a mashup of a few really clever solutions found here-- but so far I can't get the thing to work properly for all cases. The basic cases I'm testing for are:
123.1234 -- valid
'123.1234' -- valid
34N 40' 50.12" -- invalid
'34N 40' 50.12"' -- invalid
123 --valid
'123' -- valid
Here's a jsfiddle of what I've been trying: http://jsfiddle.net/zfwAj/
Seems I should have posted as an answer
isNaN() should work to filter out those ones jsfiddle.net/QYMRe
Try
/^\d+\.?\d*$/.test( str );
Fiddle here
I suggest this one:
/^-?(\d*\.\d+|\d+(\.\d+)?)$/.test(str)
This accepts negative numbers, and float like (.42)
Fiddle test
I have a question about the default behavior of JavaScript's parseFloat function in different parts of the world.
In the US, if you call parseFloat on a string "123.34", you'd get a floating point number 123.34.
If I'm developing code in say Sweden or Brazil and they use a comma instead of a period as the decimal separator, does the parseFloat function expect "123,34" or "123.34".
Please note that I'm not asking how to parse a different culture's number format in the US. I'm asking does parseFloat in Sweden or Brazil behave the same way it does inside the US, or does it expect a number in its local format? Or to better think about this, does a developer in Brazil/Sweden have to convert strings to English format before it can use parseFloat after extracting text from a text box?
Please let me know if this doesn't make sense.
parseFloat doesn't use your locale's definition, but the definition of a decimal literal.
It only parses . not ,
I'm brazilian and I have to replace comma with dot before parsing decimal numbers.
parseFloat specification
No, parseFloat is specified to parse DecimalLiterals, which use the dot as decimal separator. It does not depend on the current environment's locale settings.
It’s not just Sweden/Brazil. F.ex in US they often add commas in large numbers, like $5,762,325.25.
The parseFloat function essentially deals with decimals, not locale strings.
In general, JavaScript can sometimes convert generic strings/numbers/dates to locale-friendly formats, but not the other way around.
Complementing the answer given by FrancescoMM, you must use regex for really big numbers. String.replace using string as a parameter will replace only the first occurrence. So 999.999.999,99 becomes 999999.999.99
stringNum.replace(/\./g, "").replace(/\,/g, ".")
Source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
If you are sure it is in Brasilian format, just convert the number to US format before parsing.
function parseItalianNumber(stringNum) {
return parseFloat(stringNum.replaceAll(".","").replaceAll(",","."));
}
in Italy we also use . as a thousands separator. This removes any thousands separators, just in case (you do not want many dots around), and then converts the comma to a dot, before calling parseFloat.
Do you know if toFixed is a localized function?
I mean, will this:
var n = 100.67287;
alert(n.toFixed(2));
show "100.67" on english US OS/browsers
and "100,67" (with comma) on Italian OS/browsers?
(Italian or any other local system that uses comma as decimal separator).
Thanks!
Late addition: with Number.toLocaleString() now available on everything bar IE 10 & below, this works, albeit rather long-winded:
var n = 100.67287;
console.log(n.toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
}));
Using undefined or 'default' for the language code will use the browser default language to format the number.
See developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString for full details.
If you're free to extend the Number prototype, you could defined Number.toLocaleFixed().
No, this will always return a point. The ECMA 262-spec [15.7.4.5] states it should be a point.
You can use this:
var n = 100.67287;
alert(parseFloat(n.toFixed(2)).toLocaleString());
On my german system the result is
100,67
No sadly, there is no real solution in pure jQuery/JavaScript. You'll need Globalize. The problem is that both toFixed() and toLocaleString() take a number and return a string. So you can never use them together. :( If you call foo.toFixed(2).toLocaleString() you won't get the localization (i.e. '1.234' in en should be '1,234' in fr) because its working on the result of toFixed() which is a string, not a number. :(