Leon van der Veen
Leon van der Veen

Reputation: 1672

multiply decimal numbers in PHP

From my database I get a decimal like, 25.30.

In PHP I multiply the decimal like this, 25.30 * 6. The result is 151,8 but with a comma.

The problem is that the result gets me a comma instead of a point like 151.8.

Is there a solution to solve this and get the result with a point?

Upvotes: 0

Views: 3318

Answers (2)

Elias Van Ootegem
Elias Van Ootegem

Reputation: 76395

try var_dump(localeconv());, you'll probably see the decimal_point key is , so either (if PHP5.3>=) try locale_set_default('en_US'); or use the (deprecated) setlocale function: setlocale:

setlocale(LC_NUMERIC, 'en_US');
//or custom:
$locale = localeconv();
$locale['decimal_point'] = '.';
$setlocale(LC_ALL, $locale);

More details on the Locale class here
On the other apporach using setlocale and getting localeconv.

A hacky quick-fix might also be:

$formatted = sprintf('%.1f',25.30 * 6);

But I'd recommend you setting the locales as they should be set. Also note that on windows, setlocale(LC_ALL) uses the system locale settings, as stated in the docs:

On Windows, setlocale(LC_ALL, '') sets the locale names from the system's regional/language settings (accessible via Control Panel).

Upvotes: 2

Patrick Kostjens
Patrick Kostjens

Reputation: 5105

You want to format your number. From the manual:

string number_format ( float $number , int $decimals = 0 , string $dec_point = '.' , string $thousands_sep = ',' )

So for example in your case this would be:

print number_format($number, 1, '.', ',');

Upvotes: 2

Related Questions