Sideshow
Sideshow

Reputation: 1351

Comma in value not working when displaying price

I am having a problem displaying a price that is brought in from a PHP file by AJAX and then appended to the page via Javascript.

$('.cash1').text(parseFloat(prices[0]).toFixed(2));

This works fine until the returned value is in the thousands and contains a comma i.e. 1,123.34.

I would really like to keep the comma in the value if possible but so far the script will only return the value 1.34. I have tried using parseInt but this seems to fail in the same way.

Upvotes: 2

Views: 236

Answers (3)

catherine
catherine

Reputation: 22808

Is this ok to you?

<script> 
.............
    $('.cash1').text(numberWithCommas(prices[0].toFixed(2)));
.............. 

function numberWithCommas(x) {
     var parts = x.toString().split(".");
     parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
     return parts.join(".");
}
</script>

Upvotes: 1

Eugeny89
Eugeny89

Reputation: 3731

Suggesting you need to work with float, you need to use replace method:

var n = prices[0].replace(',','');
$('.cash1').text(parseFloat(n).toFixed(2));

If you need for some purpose those commas, I suggest making a method that will make a string with commas from a float number when needed, and working with numbers any other time.

Upvotes: 1

Greg Oks
Greg Oks

Reputation: 2730

Why do you want to parse it? Just use it as is (or as a string):

$('.cash1').text(prices[0].toString());

Upvotes: 0

Related Questions