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
ore
)
...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
How to Write a Script to Edit a JSON File
Detect If Hovering Over Element with Jquery
Why Doesn't Decodeuri("A+B") == "A B"
Is JSON Hijacking Still an Issue in Modern Browsers
Rails - How to Include JavaScript Files Only on Certain Pages
How to Do Method Overloading in Typescript
Is There a Jquery Autogrow Plugin for Text Fields
What Is Right Way to Do API Call in React Js
Create an Object from an Array of Keys and an Array of Values
Why Does the Promise Constructor Need an Executor
Capture Browser Console Logs with Capybara
In R, How to Display Value on the Links/Paths of Sankey Graph
Headless Browser for Python (JavaScript Support Required!)
Display Spinner While Datatables Table Loads Ruby on Rails
How to Geocode 20 Addresses Without Receiving an Over_Query_Limit Response
Google Maps Places API V3 Autocomplete - Select First Option on Enter