JavaScript Parse Float Is Ignoring the Decimals After My Comma

Javascript parse float is ignoring the decimals after my comma

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(',', '.'));

How can I handle float number correctly in JS?

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

How can I parse a string with a comma thousand separator to a number?

Yes remove the commas:

let output = parseFloat("2,299.00".replace(/,/g, ''));
console.log(output);

How do I stop parseFloat() from stripping zeroes to right of decimal

simple:

function decimalPlaces(float, length) {
ret = "";
str = float.toString();
array = str.split(".");
if (array.length == 2) {
ret += array[0] + ".";
for (i = 0; i < length; i++) {
if (i >= array[1].length) ret += '0';
else ret += array[1][i];
}
} else if (array.length == 1) {
ret += array[0] + ".";
for (i = 0; i < length; i++) {
ret += '0'
}
}

return ret;
}
console.log(decimalPlaces(3.123, 6));

javascript parseFloat '500,000' returns 500 when I need 500000

Nope. Remove the comma.



Related Topics



Leave a reply



Submit