Reputation: 427
I got the following problem: I got values like
2,50
1
2,99
Now I would like to separate them into 2 parts like this:
2 and 50
1 and 00
2 and 99
$euro = explode('.', $item->price)[0];
if(array_key_exists(1, explode('.', $item->price))) {
$cent = explode('.', $item->price)[1];
}
else
{
$cent = "00";
}
That's not the way I should do that I guess ;-)
There is another problem: Now I get the following values:
2 and 5
1 and 00
2 and 99
But it should be
2 and 50
1 and 00
2 and 99
Upvotes: 1
Views: 524
Reputation: 2069
If you have floats (or strings with a dot as decimal separator) as input:
$euro = (string)floor($input);
$cent = str_pad(($input - $euro) * 100, 2, "0", STR_PAD_LEFT);
In case you get strings with a comma as separator, prepend:
$input = str_replace(",", ".", $input);
Upvotes: 0
Reputation:
You could do this, a decently short way of doing it:
$x = '2.55';
$a = explode('.',$x);
$euro = $a[0];
$cent = count($a) >= 2 ? $a[1] : '00';
Output:
2 and 55
Keep in mind that you cannot have two dots in your string at this point.
Upvotes: 2
Reputation: 117
Try this:
<?php
$value = 2.50;
$big = ($value%10);
$small = ($value-$big)*100;
echo "Value: ".$value."\n";
echo "Big: ".$big."\n";
echo "Small: ".$small."\n";
Upvotes: 0