Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Different ways to round number to 2 decimal places in PHP

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 26.6k
    Comment on it

    Many times we need to format a number with two decimal points, PHP provides many solutions for rounding a number with decimal values. This tutorial list some functions which can be used to round a number with decimal values upto 2 decimal points.


    1. round() : round() function used to round a floating point number to an integer or to fixed number of decimal points.

    Example :

    <?php
    $number = 278.264;
    echo round($number, 2);
    ?>
    

    Output : 278.26


    Note : Second parameter of round function defines the number of decimal points.


    2. number_format() : Using number_format() function also we can format a number with two decimal points. number_format() takes two parameters, first is number to format and second is to define the number of decimal points.

    Example :

    <?php
    $number = 452.3682;
    echo number&#95;format($number, 2);
    ?>
    

    Output : 452.37


    3. sprintf() : sprintf() function can also be used to format the number. The sprintf() function takes two parameters, first parameter define the rule for formatting the number and the second parameter is the number to format.

    Example :

    <?php
    $var = 541;
    $number = sprintf('%.2f', $var);
    echo $number;
    ?>
    

    Output : 541.00


    4. printf() : printf() function works same as sprintf(), the difference between them is printf() prints the number directly to screen while sprintf() allows to save the formatted value to a variable.

    Example :

    <?php
    $var = .247;
    printf('%.2f', $var);
    ?>
    

    Output : 0.25


 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: