19

I get the total_amount in cart code of ecommerce web page, after I use toString function, but when I convert the 14.82 string to int number, the decimals disappear.

<script>
 var total_amount_string = <?=json_encode($cart['total_pvp'])?>;//-> 14,82
 var total_amount_int = parseInt(total_amount_string).toFixed(2); //-> 14.00(here is the error)

console.log(total_amount_string) //-> 14,82
console.log(total_amount_int) //-> 14.00
</script>

What's the matter?

Funny Frontend
  • 3,807
  • 11
  • 37
  • 56

5 Answers5

52

If the input string is "14,82" and you want the value 14.82, you'll need to convert the , to a . and then use parseFloat:

var total_amount_int = parseFloat(
        total_amount_string.replace(/,/g, ".")
    ).toFixed(2);

parseInt will only parse the leading part of the string that defines a whole number ("int" = "integer" = "whole number"), so it stops at the ,. parseFloat will parse a decimal number, but only understands . as the decimal point, not ,, even in locales where , is the decimal point.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
28

you should use parseFloat() instead of parseInt(). Because integer number is not decimal.

4

An integer has no decimal part, so any number "casted" to int will lose its decimals. You should use parseFloat if you want to keep the decimal part. On the other hand, make sure you are not using a comma: Javascript parse float is ignoring the decimals after my comma

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
0

Your number is using a "," separator. Unfortunately there is no locale settings for number parsing in JavaScript, so you are forced to a bit more hacky:

var total_amount_string = "14,823462";
var total_amount_float = parseFloat(total_amount_string.replace(",", ".")).toFixed(2);

document.getElementById("total_amount_string").innerText = total_amount_string;
document.getElementById("total_amount_float").innerText = total_amount_float;
total_amount_string: <span id="total_amount_string"></span>
<br />
total_amount_float: <span id="total_amount_float"></span>
Staale
  • 27,254
  • 23
  • 66
  • 85
-2

The parseInt() function parses a string and returns an integer. ParseInt returns only the first number in the string is returned!. If the first character cannot be converted to a number, parseInt() returns NaN.

Seth McClaine
  • 9,142
  • 6
  • 38
  • 64
Wintergreen
  • 236
  • 1
  • 9