1

So my problem is that php is not casting these types correctly.. I need to figure out a better way of doing it than number 3, if there is one, and I'd really like to know why PHP treats the comma as a period or something.

$cost = "7,800.00"; // "7,800.00"
$cost = (int) "7,800.00" // int(7)
$cost = (int) preg_replace('/[^-0-9\.]/i', '', "7,800.00"); // int(7800)

Edit, to make things clear to those who don't read: I'm looking for a more elegant way to do this. As far as why this behavior exists, I've already gotten the explanation I was looking for. Thanks.

Kavi Siegel
  • 2,964
  • 2
  • 24
  • 33
  • I don't believe there is no int value for a comma, maybe a monetary format? money_format() – Phill Pafford Aug 10 '11 at 18:08
  • 1
    Have you considered removing only the commas in your strings? Commas make them ambiguous since they are the decimal point character in some countries but not others. Why do you not want to do #3? Just wrap it in a function for reuse. – Dan Grossman Aug 10 '11 at 18:08
  • what is the problem ? there is not problem on this question – ajreal Aug 10 '11 at 18:11
  • possible duplicate of [PHP money string conversion to integer error](http://stackoverflow.com/questions/193593/php-money-string-conversion-to-integer-error) – Phill Pafford Aug 10 '11 at 18:12
  • There is no problem, ajreal. I'm trying to learn why php works like that, and Dan Grossman had quite a perfect answer to that. I'm not a fan of my third option because it just doesn't seem as elegant as it could be, however, I suppose if there is no more simplified way of doing it I can settle for that. – Kavi Siegel Aug 10 '11 at 18:15

1 Answers1

0

PHP does not know what to do with the grouping characters (in this case a comma) as it is not a numeric character, period, or e for exponentiation. So the functions stop parsing when the first non-relevant character is read.

Second, have a look at the numeric functions PHP provides: floatval and intval

steveo225
  • 11,394
  • 16
  • 62
  • 114