How to round to two decimal places PHP

14,628

Solution 1

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;

Solution 2

round ($your_variable, 2)

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

Solution 3

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
Share:
14,628
jeremy
Author by

jeremy

Updated on June 04, 2022

Comments

  • jeremy
    jeremy almost 2 years

    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_state[values][submitted][10]);
    $form_values['submitted'][11] = $bmi;
    $form_values['submitted_tree'][11] = $bmi;
    

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