Javascript toFixed localized? - javascript

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. :(

Related

Sanitize javascript array element

Is there something i can do here
const ecommerce = {
purchase: {
actionField: {
},
},
}
As it looks like, the inputted value is a string. You could convert the string to number by using an unary plus + in front of the variable.
name: "PRICEPLAN-" + +price,
An other way would include some sanity checks and urges the user to input a valid value.
#Nina Scholz' answer is correct and concise. The other way in JavaScript to do this, and which I personally prefer because it's more semantic, is to use Number().
name: "PRICEPLAN-" + Number(price),
I find that good semantics make it easier for others to understand my code (and for me too, when I come back to it 6 months later.)
As others have pointed out, this will not coerce your values to an integer, so you will want to be sure about your inputs.
If you want Integer value, then you can use var parseInt() function in JS
var a = parseInt("10.00")
will convert it to "10"
radix :
An integer between 2 and 36 that represents the radix (the base in mathematical numeral systems) of the above mentioned string. Specify 10 for the decimal numeral system commonly used by humans. Always specify this parameter to eliminate reader confusion and to guarantee predictable behavior.
After adding radix it will assure the output will be decimal :
var a = parseInt("010.00", 10)
To be sure to have an Interger, use parseInt(). As Number() won't prevent numbers like 3.11 to be transformed to Integers.
name: "PRICEPLAN-" + parseInt(price),
And using ES6 template notation:
name: `PRICEPLAN-${parseInt(price)}`,

Round float and then to locale string

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?

why is 10 * (7/10) = 7 in JavaScript?

7 and 10 in the expression (7/10) are integers, so the result 0.7 should be integer as well, which is 0, and the result for the entire expression should be 0 too. However, it's giving me the result of 7, why? Is it ignoring the parentheses or converts to double automatically?
JavaScript doesn't distinguish between integers and floating point numbers, everything I believe is considered a double so that is just why you get the result.
Take a look at the details on the Number property on MDN.
JavaScript doesn't have an integer type, or a double, or a float... it just has 1 type for all numbers: the helpfuly called Number type (try var foo = new Number(7);, or var foo = Number('123string');
Now, I know I said that JS doesn't know of floats, but that's not entirely true. All Number type vars/values are, essentially 64 bit floats, as defined by the IEEE 754 standard (which are, indeed, as Jan Dvorak kindly pointed out to me, double's in most staticly typed languages), with all the caveats that brings with it:
(.1 + .2);//0.30000000000000004
But that's not the point. The point is that, in JS you can perform float + int arithmatic without there ever being a need for internal casts, or conversions. That's why 10*(7/10) will always be 7
There is no int and double in JavaScript
In JavaScript, both int, flot, and double are normalized to work together. They are treated as 1 (They're treated as as Number, which is an IEEE 754 float. Thanks #Elias Van Ootegem). Equality, Liberty and Fraternity. and thus;
10*0.7 = 7
JavaScript is not like C.
Javascript doesn't have integers, and even if it did, there's nothing that says that / needs to return an integer (just because another language may do that doesn't mean every language has to). The operation results in a float/Number, just like all Javascript numbers are, period.
try this
10*parseInt(7/10)
hope this will help you
If you try to follow the rules, then
10 * (7/10) --> 10 * .7 --> 7
You cannot change the way its gonna result into.
so the result 0.7 should be integer as well, which is 0
If you want this, then try using
Math.Floor();
This would change the decimals to the nearest int! Or try out parse()
JavaScript uses dynamic types. That means that a variable like this:
var str = "hi";
Can later become:
str = 123; //now we have an 'int'
str += 0.35; //now str is 123.35, a 'float'
So JavaScript doesn't cast floats to ints for example.
If you want to force a "cast" then you have to do:
var integer = parseInt( 3.14*9.0291+23, 10 ); //the second parameter (10) is the 'base'
But remember, Javascript will not take care of types, that's your problem.

javascript/jquery: quick way to retrieve numeric from length attributes

I have attributes which denotes "5 px", "8px" "6em" and possible some others which I currently cannot think of right now.
I'm interested in only the numeric value (ie 5, 8 or 6.) I know i can do some regex but I'm wondering is there a short, documented, cross browser and readable jquery / javascript function out there which already provides this?
regards,
Jeroen.
PS not sure if the wording in the title is correct please advice for alternatives.
Use parseInt function:
var str = '5px';
alert(parseInt(str, 10)); // 5
Note that second argument of 10 represents base 10 there.
In case they ever come back as 08px, (leading zero), use the radix of 10. Otherwise parseint() thinks your number is in octal.
var value = parseInt(str, 10);
It is probably never going to happen being returned from jQuery as a CSS property value, but a good habit to get into.
A combination of parseInt/parseFloat (see the other answers) is probably your best bet, but just for kicks (and if you want to make your code completely unreadable), you can always use a Regex with extra cheese:
+(str.match(/(-?\d+(?:\.\d+)?)/)||[,0])[1]
The + operator converts the result to a Number, ||[,0] provides a default array if there's no number in str. [,0] might not work in all browsers, but [0,0] will.
:)

How to compare locale dependent float numbers?

I need to compare a float value entered in a web form against a range. The problem is that the client computers may have various locale settings, meaning that user may use either "." or "," to separate the integer part from decimal one.
Is there a simple way to do it? As it is for an intranet and that they are only allowed to use IE, a VBScript is fine, even if I would prefer to use JavaScript.
EDIT: Let me clarify it a bit:
I cannot rely on the system locale, because, for example, a lot of our french customers use a computer with an english locale, even if they still use the comma to fill data in the web forms.
So I need a way to perform a check accross multiple locale "string to double" conversion.
I know that the raise condition is "what about numbers with 3 decimal digits", but in our environment, this kind of answer never happen, and if it happens, it will be threated as an out of range error due to the multiplication by a thousand, so it's not a real issue for us.
In Javascript use parseFloat on the text value to get a number. Similarly in VBScript use CDbl on the text value. Both should conform to the current locale settings enforce for the user.
This code should work:
function toFloat(localFloatStr)
var x = localFloatStr.split(/,|\./),
x2 = x[x.length-1],
x3 = x.join('').replace(new RegExp(x2+'$'),'.'+x2);
return parseFloat(x3);
// x2 is for clarity, could be omitted:
//=>x.join('').replace(new RegExp(x[x.length-1]+'$'),'.'+x[x.length-1])
}
alert(toFloat('1,223,455.223')); //=> 1223455.223
alert(toFloat('1.223.455,223')); //=> 1223455.223
// your numbers ;~)
alert(toFloat('3.123,56')); //=> 3123.56
alert(toFloat('3,123.56')); //=> 3123.56
What we do is try parsing using the culture of the user and if that doesn't work, parse it using an invariant culture.
I wouldn't know how to do it in javascript or vbscript exactly though.
I used KooiInc's answer but change it a bit, because it didn't reckon with some cases.
function toFloat(strNum) {
var full = strNum.split(/[.,]/);
if (full.length == 1) return parseFloat(strNum);
var back = full[full.length - 1];
var result = full.join('').replace(new RegExp(back + '$'), '.' + back);
return parseFloat(result);
}
Forbid using any thousands separator.
Give the user an example: "Reals should look like this: 3123.56 or 3123,56". Then simply change , to . and parse it.
You can always tell user that he did something wrong with a message like this:
"I don't understand what you mean by "**,**,**".
Please format numbers like "3123.56."

Categories

Resources