schapel Posted December 22, 2009 Share Posted December 22, 2009 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! Link to comment https://forums.phpfreaks.com/topic/186068-i-need-to-add-two-numbers-together-but-they-are-in-string-format/ Share on other sites More sharing options...
mrMarcus Posted December 22, 2009 Share Posted December 22, 2009 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)))); ?> Link to comment https://forums.phpfreaks.com/topic/186068-i-need-to-add-two-numbers-together-but-they-are-in-string-format/#findComment-982621 Share on other sites More sharing options...
schapel Posted December 22, 2009 Author Share Posted December 22, 2009 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. Link to comment https://forums.phpfreaks.com/topic/186068-i-need-to-add-two-numbers-together-but-they-are-in-string-format/#findComment-982636 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.