简体   繁体   中英

PHP float number with decimal point rounding

I am calculating few numbers (sales_total, service_charge) to get 7% GST. What I get is number with decimal point.

Example 1:

$sales_total        = 207.50;
$service_charge = 20.75;

$gst                = ($sales + $sc) * .07;

Returns me GST = 15.9775 .

Example 2:

$sales_total        = 28;
$service_charge = 2.8;
$gst                =  ($sales + $sc) * .07;

Returns me GST = 2.156

I need to match the data with a report where the

  • Example 1 GST = 16.00 (my 15.9775)
  • Example 2 GST = 2.15 (my 2.156)

I am trying php round , number_format functions but not getting both of my results correct. round gives example 1 result correct, number_format gives example 2 correct.

What I am doing wrong, or which function I need to use?

Have you tried:

round($gst, 2);

this will round your variable within 2 decimal houses.

Could you try?

Edit

Since you want different behaviors in both values I don't think that round can help you in both situations. Actually the second example you don't even want a round. You just want to delete the 3rd decimal number so...

In this case I would use the 1st example the round with 2 decimal houses as I said and in the 2nd example I would just delete the 3rd house number or limit in the database>table the float number to 2 decimal houses.

I believe you're probably needing to round with precision decimal places away from zero, so depending on that you could use:

$gst = sprintf("%.2f", round($gst, 3 - strlen(round($gst)), PHP_ROUND_HALF_ODD));

Result:

16.00
2.16

This shows a precision of 3 decimal places away from zero minus the length of the rounded value. You'll likely need to play around with the rounding mode and precision to get it how you want. The result of 2.15 from 2.156 looks incorrect — it's unclear how you've gotten this value.

  • PHP_ROUND_HALF_UP • Round val up to precision decimal places away from zero, when it is half way there. Making 1.5 into 2 and -1.5 into -2.

  • PHP_ROUND_HALF_DOWN • Round val down to precision decimal places towards zero, when it is half way there. Making 1.5 into 1 and -1.5 into -1.

  • PHP_ROUND_HALF_EVEN • Round val to precision decimal places towards the next even value.

  • PHP_ROUND_HALF_ODD • Round val to precision decimal places towards the next odd value.

Reference: http://php.net/manual/en/function.round.php

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