简体   繁体   中英

What is the best way to move decimal point in PHP

I'm working on project where you can make payments with credit card. I have booking system from what I get "price" and then it sends this price to merchant online payment page. My problem is that booking system sends price in decimal. Like 123.45 . But merchant accepts only this format: 12345 . And after receiving this format it ads decimal point automatically.

I need to convert this "price" without decimal point. In other words move it to right. What is the best function or solution to do that?

For now I'm using round() function and add two zeros (00). But this way is only if I really use rounded up prices.

$price = $_POST['price'];

$price = round($price) . '00';

I expect the output 123.45 to be 12345 . Other example 123.00 to be 12300 .

Careful... you may lose precision. I had to switch to using bcmul()

 $version=22.0220;
 $int1=(int)($version*10000); // $int1 is 220219 (oops)
 $int2=(int)(bcmul($version,10000)); // $int2 is 220220 (correct)
<?php
   $withoutDecimal = $withDecimal * 100;
?>

For those who need more flexible solution. For example, Bitcoin has 8 decimal places, US dollar - 2

function price_minor_units($dollars, $decimals = 2)
{
    return $dollars * (10 ** $decimals);
}

function price_major_units($cents, $decimals = 2){
    return $cents / (10 ** $decimals);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM