tags:

views:

104

answers:

3

PHP can't recognize 1,200.00(generated by number_format) but only 1200.00,

What's the general solution for this problem?

+1  A: 

You could do $num = (float) str_replace(',', '', $num); Basically, just get rid of the commas, and then cast it as a numeric type (float or int).

ircmaxell
What if the program is run in Germany which you may get `1.200,00`?
KennyTM
`$locale = localeconv();`, Then change the `','` in above to `$locale['thousands_sep']`...
ircmaxell
A: 

You could remove any character that is not a digit or a decimal point and parse that with floatval:

$number = 1200.00;
$parsed = floatval(preg_replace('/[^\d.]/', '', number_format($number)));
var_dump($number === $parsed);  // bool(true)

And if the number has not . as decimal point:

function parse_number($number, $dec_point=null) {
    if (empty($dec_point)) {
        $locale = localeconv();
        $dec_point = $locale['decimal_point'];
    }
    return floatval(str_replace($dec_point, '.', preg_replace('/[^\d'.preg_quote($dec_point).']/', '', $number)));
}
Gumbo
+5  A: 

If you're using 5.3 or higher (thanks ircmaxell), use numfmt_parse.

Donnie
`PHP Fatal error: Call to undefined function numfmt_parse()`
It's only available in 5.3+ or if you install a PECL extension...
ircmaxell