simple regex in php, formatting decimal number

前端 未结 5 748
抹茶落季
抹茶落季 2020-12-06 22:38

I need to convert numbers to have .00 after them, but only if the number is an integer, or it has just 1 number after the decimal point, like so:

1.4 = 1.40
         


        
相关标签:
5条回答
  • 2020-12-06 23:06
    $num = 0.00638835;
    
    $avg = sscanf($num,"%f")[0] /100;
    
    echo sprintf("%.10f", $avg);
    
    result 0.0000638835
    
    0 讨论(0)
  • 2020-12-06 23:16

    Check out PHP's built-in function number_format

    You can pass it a variable and it'll format it to the correct decimal places

        $number = 20;
        if (is_int($number)) {
            $number = number_format($number, 2, '.', '');
        }
    
    0 讨论(0)
  • 2020-12-06 23:17

    You can also use printf or sprintf

    printf("%01.2f", '34.77');
    $formatted_num = sprintf("%01.2f", '34.77');
    
    0 讨论(0)
  • 2020-12-06 23:19
    number_format($number, 2, '.', '');
    

    Read more at PHP.net. You don't need to determine if a number is an integer or not -- as long as it's a number, it will be formatted to two decimal places.

    If you'd like the thousands separator, change the last parameter to ','.

    0 讨论(0)
  • 2020-12-06 23:22

    read number_format

    number_format($number, 2, '.', '');
    
    0 讨论(0)
提交回复
热议问题