开发者

Dollars to pennies

I'm having some trouble with Regex I'm trying to take a money amount like $28.84 and store it into my da开发者_StackOverflowtabase as pennies. Right now I'm using this

$amount="$28.84";
$amount_number= ereg_replace("[(^0-9)(.)(0-9){2}]", "", $amount ); //return a decimal
$store_amount = $amount_number*100; //get number of pennies 

I'm also trying to strip the number of "," " " and anything not a decimal number.


I think you are going about this wrong. Why not replace the dollar sign, use floatval and then multiply by 100. Then use intval to get rid of the decimal from the result, as you don't want fractions of a penny.

$amount = intval(floatval(str_replace("$", "", $amount))*100);

I didn't test it, but something like this should work.

Check out here for how some people handle currency stuff. They have a lot of methods:
http://php.net/manual/en/function.floatval.php


Assuming the input has been validated already, remove all non-digits then convert the result to an integer using int_val.

Personally I would reject all non-standard inputs such as $12.3. In my opinion when dealing with money you should be strict on what inputs you accept and not try to guess what was meant.


[(^0-9)(.)(0-9){2}]

should be

[0-9.]

You cannot use () inside []. The only special character that can be used inside [] is the ^ character.


$amount = "$28.84";
$amount = preg_replace("#([^0-9\.]+)#", "", $amount);
$amount = explode(".", $amount);
$amount = (intval($amount[0]) * 100) + intval($amount[1]);
echo $amount; //2884


Why don't you just remove the dollar sign and multiple by 100?

preg_replace(/\$/, "", $amount);


Try chaning second line to as follows:

$amount_number= ereg_replace("[^0-9.]", "", $amount ); 


$amount = "$28.84";
$amount_number = floatval(substr($amount,1));
$store_amount = $amount_number*100.0;

You can just use substr to remove the dollar sign. If you really want to use a regex, try this:

$amount = "$28.84";
$amount_number = floatval(preg_replace('/[^\d\.]/', '', $amount));
$store_amount = $amount_number*100.0;

You need to use floatval to convert the amount from a string to a float.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜