Biker John
Biker John

Reputation: 2711

Change decimal float character

I have a variable $num='1.000,00'; which is ONE THOUSAND in europe.

I would like to get 20% of this number $num*0.2;, but i get wrong results since there is dot used in the string instead of comma.

I tried the number_format function but converted my thousand to 1 instead of 1000.

I would like a final result back in european form after the percentage is calculated. (200,00).

Upvotes: 0

Views: 135

Answers (2)

Sven van Zoelen
Sven van Zoelen

Reputation: 7229

$num = '1.000,50';

echo floatval(str_replace(array('.', ','), array('', '.'), $num)) * .2;

Edit after comment Axel

You can better work with floats. Why use strings? Use the real floats for all the math operations and transform the float to the whished format when viewing it to the user.

Like so:

$val = 1000.20;
$new_val = $val * .2;

setlocale(LC_MONETARY, 'nl_NL');
echo money_format('%(#10n', $new_val);

Results in EUR 200,04

More info money_format

Upvotes: 1

claustrofob
claustrofob

Reputation: 4984

$num = str_replace(array('.', ','), array('', '.'), $num);

Upvotes: 0

Related Questions