开发者

PHP - Commercial round

I want to make commercial round to prices (with PHP)

For example :

15.55 becomes 15.60

15.54 b开发者_StackOverflow中文版ecomes 15.50

147.77 becomes 147.80

==> Always zero in the end.

How can I do that ?

Thanks a lot.


Use the precision parameter of php's round function.

$result = number_format(round(15.5, 1), 2);

See:

http://php.net/manual/en/function.round.php http://php.net/manual/en/function.number-format.php


You can act in two steps :

  • first, use round() to round your values to one decimal : 15.6
  • and, then, use number_format() to display them with two decimals (and thousand separators, if needed)


For example, the following portion of code :

var_dump( number_format( round(15.55, 1), 2) );
var_dump( number_format( round(15.54, 1), 2) );
var_dump( number_format( round(147.77, 1), 2) );

Will give you :

string '15.60' (length=5)
string '15.50' (length=5)
string '147.80' (length=6)


Use round() http://php.net/manual/en/function.round.php with all 3 parameters

round($number, 2, PHP_ROUND_HALF_UP);

the zero can be added via number_format()


$result = sprintf('%.2F', round($val, 1));

sprintf() does the same as number_format() in this case.


Try:

$rounded = ceil($number * 10) / 10;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜