22

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?

1
  • it is because of the , in 14,82... what is the expected value... Commented Mar 6, 2015 at 8:37

5 Answers 5

56

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.

Sign up to request clarification or add additional context in comments.

Comments

30

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

Comments

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

Comments

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>

Comments

-3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.