如何舍入到小数点后两位PHP

时间:2011-03-20 23:03:50

标签: php drupal decimal drupal-webform

我想在PHP中将数字四舍五入到小数点后两位。

PHP代码:

$bmi = ($form_state[values][submitted][1] * 703) / 
    ($form_state[values][submitted][10] * $form_state[values][submitted][10]);
$form_values['submitted'][11] = $bmi;
$form_values['submitted_tree'][11] = $bmi;

对变量$bmi进行舍入的最佳方法是什么?

3 个答案:

答案 0 :(得分:9)

答案 1 :(得分:4)

EDIT3:

如果我理解你的代码,那么它应该是这样的:

<?php
    //Calculate $bmi
    $bmi = ($form_state[values][submitted][1] * 703) / 
       ($form_state[values][submitted][10] * $form_state[values][submitted][10]);

    //Fill unrounded $bmi var into array for whatever reason
    $form_values['submitted'][11] = $bmi;

    //Fill unrounded $bmi var into array for whatever reason
    $form_values['submitted_tree'][11] = $bmi;

    //$bmi contains for example 24.332423
    $bmi = round($bmi,2);

    //Should output 24.33
    echo $bmi;
?>

如果出现任何问题,我只能假设计算出的$ bmi var在某个地方搞砸了。

是否应该将未填入的值填入$ form_values ['submitted'] [11]?如果没有尝试以下:

 $bmi = ($form_state[values][submitted][1] * 703) / ($form_state[values][submitted][10] *  
 $bmi = round($bmi,2); 
 $form_values['submitted'][11] = $bmi;
 $form_values['submitted_tree'][11] = $bmi;

答案 2 :(得分:3)

PHP round将取一个数字并将其四舍五入为精度:

$foo = 105.5555;
echo round($foo, 2);                    //prints 105.56

或一个字符串并将其四舍五入为精度:

$bmi = "52.44444";
echo round($bmi, 2);                    //prints 52.44

舍入到两个单位精度,并以这种方式强制最小精度:

$foo = 105.5555;
echo number_format(round($foo, 2), 4, '.', '');  //prints 105.5600