开发者

How to round to two decimal places PHP

I would like to round a number to two decimal places in PHP.

PHP code:

$bmi = ($form_state[values][submitted][1] * 703) / 
    ($form_state[values][submitted][10] * $form_st开发者_运维百科ate[values][submitted][10]);
$form_values['submitted'][11] = $bmi;
$form_values['submitted_tree'][11] = $bmi;

What is the best way to round the variable $bmi?


round ($your_variable, 2)

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


Edit3:

Well if I understand your code right it should go like this:

<?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;
?>

If anything goes wrong I can only assume that the calculated $bmi var gets messed up somewhere.

Is it supposed that you fill the unrounded value into $form_values['submitted'][11]? if not try the following:

 $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;


PHP round will take a number and round it to 2 units precision:

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

Or a string and round it to 2 units precision:

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

Round to two units precision, and force a minimum precision this way:

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜