Search code examples
phpcurrency

PHP: Calculate with cents


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

Solution

  • 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.