parseFloat("2,83") will return 2 because , is not recognized as decimal separator, while . is.
If you want to round the number to 2 decimal places just use parseFloat(discval.toFixed(2)) or Math.round(discval * 100) / 100;
If you need this jut for display purposes, then leave it as a string with a comma. You can also use Number.toLocaleString() to format numbers for display purposes. But you won't be able to use it in further calculations.
BTW .toFixed() returns a string, so no need to use .toString() after that.
parseFloat("2,83") will return 2 because , is not recognized as decimal separator, while . is.
If you want to round the number to 2 decimal places just use parseFloat(discval.toFixed(2)) or Math.round(discval * 100) / 100;
If you need this jut for display purposes, then leave it as a string with a comma. You can also use Number.toLocaleString() to format numbers for display purposes. But you won't be able to use it in further calculations.
BTW .toFixed() returns a string, so no need to use .toString() after that.
From https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseFloat
parseFloat parses its argument, a string, and returns a floating point number. If it encounters a character other than a sign (+ or -), numeral (0-9), a decimal point, or an exponent, it returns the value up to that point and ignores that character and all succeeding characters. Leading and trailing spaces are allowed.
If the first character cannot be converted to a number, parseFloat returns NaN.
, is not an expected character so the number is truncated to that.
It's not possible to change the representation of floating point numbers in Javascript, you will need to treat your number as a string if you want to separate decimals with a comma instead of dot.
Javascript Formatting numbers with commas
parsefloat - Javascript parse float is ignoring the decimals after my comma - Stack Overflow
jquery - Convert String with Dot or Comma as decimal separator to number in JavaScript - Stack Overflow
How to replace a comma for a dot and a dot for a comma - Post.Byes
You can use ".toFixed(x)" function to round your prices:
price1 = price1.toFixed(2)
And then you can use method ".toString()" to convert your value to string:
price1 = price1.toString()
Also, you can use method ".replace("..","..")" to replace "." for ",":
price1 = price1.replace(".", ",")
Result:
price1 = price1.toFixed(2).toString().replace(".", ",")
Updated answer
.toFixed already returns a string, so doing .toString() is not needed. This is more than enough:
price1 = price1.toFixed(2).replace(".", ",");
Try this:
var price1 = 1.99234;
// Format number to 2 decimal places
var num1 = price1.toFixed(2);
// Replace dot with a comma
var num2 = num1.toString().replace(/\./g, ',');
This is "By Design". The parseFloat function will only consider the parts of the string up until in reaches a non +, -, number, exponent or decimal point. Once it sees the comma it stops looking and only considers the "75" portion.
- https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseFloat
To fix this convert the commas to decimal points.
var fullcost = parseFloat($("#fullcost").text().replace(',', '.'));
javascript's parseFloat doesn't take a locale parameter. So you will have to replace , with .
parseFloat('0,04'.replace(/,/, '.')); // 0.04
Do a replace first:
parseFloat(str.replace(',','.').replace(' ',''))
I realise I'm late to the party, but I wanted a solution for this that properly handled digit grouping as well as different decimal separators for currencies. As none of these fully covered my use case I wrote my own solution which may be useful to others:
function parsePotentiallyGroupedFloat(stringValue) {
stringValue = stringValue.trim();
var result = stringValue.replace(/[^0-9]/g, '');
if (/[,\.]\d{2}$/.test(stringValue)) {
result = result.replace(/(\d{2})$/, '.$1');
}
return parseFloat(result);
}
This should strip out any non-digits and then check whether there was a decimal point (or comma) followed by two digits and insert the decimal point if needed.
It's worth noting that I aimed this specifically for currency and as such it assumes either no decimal places or exactly two. It's pretty hard to be sure about whether the first potential decimal point encountered is a decimal point or a digit grouping character (e.g., 1.542 could be 1542) unless you know the specifics of the current locale, but it should be easy enough to tailor this to your specific use case by changing \d{2}$ to something that will appropriately match what you expect to be after the decimal point.
Use replace with callback function which will replace , by . and . by ,. The returned value from the function will be used to replace the matched value.
var mystring = "1,23,45,448.00";
mystring = mystring.replace(/[,.]/g, function (m) {
// m is the match found in the string
// If `,` is matched return `.`, if `.` matched return `,`
return m === ',' ? '.' : ',';
});
//ES6
mystring = mystring.replace(/[,.]/g, m => (m === ',' ? '.' : ','))
console.log(mystring);
document.write(mystring);
Regex: The regex [,.] will match any one of the comma or decimal point.
String#replace() with the function callback will get the match as parameter(m) which is either , or . and the value that is returned from the function is used to replace the match.
So, when first , from the string is matched
m = ',';
And in the function return m === ',' ? '.' : ',';
is equivalent as
if (m === ',') {
return '.';
} else {
return ',';
}
So, basically this is replacing , by . and . by , in the string.
Nothing wrong with Tushar's approach, but here's another idea:
myString
.replace(/,/g , "__COMMA__") // Replace `,` by some unique string
.replace(/\./g, ',') // Replace `.` by `,`
.replace(/__COMMA__/g, '.'); // Replace the string by `.`
Hiya demo http://jsfiddle.net/9Ry9t/ or http://jsfiddle.net/ZtkBW/2/ or http://jsfiddle.net/HJnLD/
Bit different from your solution but if you keen to use this, it will not allow any characters to type in the text box.
The solution does full validation for numbers and for float it will not take (dot)
code sample
$('.number').keypress(function(event) {
if(event.which < 46
|| event.which > 59) {
event.preventDefault();
} // prevent if not number/dot
if(event.which == 46
&& $(this).val().indexOf('.') != -1) {
event.preventDefault();
} // prevent if already dot
});
Here's a really terrible if statement to circumvent the fact that parseFloat can parse the first number it finds in a string and indexOf only returns the first index of a character (not all indexes).
It would probably be smarter to store the value of $(this).val() in a variable but I'll leave that as an exercise to the reader. (don't have time right now)
if(!isNaN(parseFloat($(this).val()) && $(this).val().indexOf(".") > -1 && $(this).val().indexOf(".") == $(this).val().lastIndexOf(".")) {
// do something, your value is a valid float
}