Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: Converting dollars to cents

As input, I want to accept any of the following: "$12.33", "14.92", "$13", "17", "14.00001". As output, I want 1233, 1492, 1300, 1700 and 1400 respectively. This is apparently not as easy as it looks:

<?php
$input = '$64.99';  // value is given via form submission
$dollars = str_replace('$', '', $input);  // get rid of the dollar sign
$cents = (int)($dollars * 100) // multiply by 100 and truncate
echo $cents;
?>

This outputs 6498 instead of 6499.

I assume this has to do with inaccuracies in floating point values, and avoiding these is the whole reason I'm converting to integer cents in the first place. I suppose I could use logic like "get rid of the $ sign, check if there's a decimal point, if so, check how many characters there are after it padding to two and truncating after that then remove the period, if there wasn't one append two zeros and hope for the best" but using string operations for this seems ridiculous.

Surely taking a monetary value from a form and storing it as cents in a database is a common use case. Surely there is a "reasonable" way of doing this.

Right? .....right? :<

like image 383
Mala Avatar asked Feb 12 '14 17:02

Mala


People also ask

How many cents means 1 dollar?

One dollar equals 100 cents. Dollars are in paper notes called bills and come in $100, $50, $20, $10, $5 and $1.


2 Answers

Consider using the BC Math extension, which does arbitrary-precision math. In particular, bcmul():

<?php
$input = '$64.99';
$dollars = str_replace('$', '', $input);
$cents = bcmul($dollars, 100);
echo $cents;
?>

Output:

6499
like image 177
cdhowie Avatar answered Oct 05 '22 01:10

cdhowie


$test[] = 123;
$test[] = 123.45;
$test[] = 123.00;
$test[] = 123.3210123;
$test[] = '123.3210123';
$test[] = '123,3210123';
$test[] = 0.3210;
$test[] = '00.023';
$test[] = 0.01;
$test[] = 1;


foreach($test as $value){
    $amount = intval(
                strval(floatval(
                    preg_replace("/[^0-9.]/", "", str_replace(',','.',$value))
                ) * 100));
    echo $amount;
}

Results:

12300
12345
12300
12332
12332
12332
32
2
1
100
like image 43
btavares Avatar answered Oct 05 '22 01:10

btavares