Jump to content

I need to add two numbers together, but they are in string format?


schapel

Recommended Posts

Hello:

 

I'm sure this is an easy question for most of you, but is causing me problem for some reason.

 

I need to add two numbers together, both of which are already converted to a string for other uses.  Meaning the first number is "3,000" and the second could be "1,500" (notice the commas).  If I try to just add them it doesn't correctly show '4500' like I need, I suspect it has something to do with the commas that are in the string.

 

Any thoughts? Thanks!

you should always keep numbers in the raw format (without additional formatting, ie. , . etc.).  this preserves the actual number.  and if you want to fancy up the number, just use number_format .. it will add formatting (commas, decimal points, etc.), to the number.

 

short of any real thought going into this, just remove the commas and do your math:

 

<?php
$a = "1,500";
$b = "3,000";

echo number_format ((str_replace (',', '', $a) + (str_replace (',', '', $b))));
?>

That's what I was looking for.  I'm actually working with a pre-done system so the data was already formatted in a bunch of other places in the script which I didn't want to mess with.  Your code above did the trick, I forgot about str_replace, thanks.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.