dpp3047
dpp3047
2011-05-18 12:42

php中的简单正则表达式,格式化十进制数

已采纳

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
45 = 45.00
34.77 = 34.77

What reg exp to use for this simple case?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

5条回答

  • dsc862009 dsc862009 10年前
    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 ','.

    点赞 评论 复制链接分享
  • dqwh2717 dqwh2717 4年前
    $num = 0.00638835;
    
    $avg = sscanf($num,"%f")[0] /100;
    
    echo sprintf("%.10f", $avg);
    
    result 0.0000638835
    
    点赞 评论 复制链接分享
  • douxing6532 douxing6532 10年前

    You can also use printf or sprintf

    printf("%01.2f", '34.77');
    $formatted_num = sprintf("%01.2f", '34.77');
    
    点赞 评论 复制链接分享
  • doubaben7394 doubaben7394 10年前

    read number_format

    number_format($number, 2, '.', '');
    
    点赞 评论 复制链接分享
  • douchun1859 douchun1859 10年前

    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, '.', '');
        }
    
    点赞 评论 复制链接分享

相关推荐