In PHP, how to print a number with 2 decimals, but only if there are decimals already?

前端 未结 6 992
抹茶落季
抹茶落季 2021-01-14 08:33

I have a basic index.php page with some variables that I want to print in several places - here are the variables:



        
相关标签:
6条回答
  • 2021-01-14 09:02

    This is simple and it will also let you tweak the format to taste:

    $var = sprintf($var == intval($var) ? "%d" : "%.2f", $var);
    

    It will format the variable as an integer (%d) if it has no decimals, and with exactly two decimal digits (%.2f) if it has a decimal part.

    See it in action.

    Update: As Archimedix points out, this will result in displaying 3.00 if the input value is in the range (2.995, 3.005). Here's an improved check that fixes this:

    $var = sprintf(round($var, 2) == intval($var) ? "%d" : "%.2f", $var);
    
    0 讨论(0)
  • 2021-01-14 09:06
    <?php
    
    $number = 1234.56;
    
    // english notation (default)
    $english_format_number = number_format($number);
    // 1,235
    
    // French notation
    $nombre_format_francais = number_format($number, 2, ',', ' ');
    // 1 234,56
    
    $number = 1234.5678;
    
    // english notation without thousands seperator
    $english_format_number = number_format($number, 2, '.', '');
    // 1234.57
    
    ?>
    

    more info here http://php.net/manual/en/function.number-format.php

    0 讨论(0)
  • 2021-01-14 09:07

    you can use number_format():

    echo number_format($firstprice, 2, ',', '.');
    
    0 讨论(0)
  • 2021-01-14 09:11

    Alternatively way to print

    $number = sprintf('%0.2f', $numbers); 
       // 520.89898989 -> 520.89
    
    0 讨论(0)
  • 2021-01-14 09:17

    You could use

       if (is_float($var)) 
       {
         echo number_format($var,2,'.','');
       }
       else
       {
         echo $var;
       }
    
    0 讨论(0)
  • 2021-01-14 09:23

    What about something like this :

    $value = 15.2; // The value you want to print
    
    $has_decimal = $value != intval($value);
    if ($has_decimal) {
        echo number_format($value, 2);
    }
    else {
        echo $value;
    }
    


    Notes :

    • You can use number_format() to format value to two decimals
    • And if the value is an integer, just display it.
    0 讨论(0)
提交回复
热议问题