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

时间:2021-01-21 21:46:39

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:

我需要在它们之后将数字转换为.00,但仅当数字是整数时,或者它在小数点后只有1个数字,如下所示:

1.4 = 1.40
45 = 45.00
34.77 = 34.77

What reg exp to use for this simple case?

reg exp用于这个简单的案例?

5 个解决方案

#1


1  

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.

在PHP.net上阅读更多内容。您不需要确定数字是否为整数 - 只要它是一个数字,它将被格式化为两个小数位。

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

如果您想要千位分隔符,请将最后一个参数更改为“,”。

#2


2  

You can also use printf or sprintf

您也可以使用printf或sprintf

printf("%01.2f", '34.77');
$formatted_num = sprintf("%01.2f", '34.77');

#3


1  

Check out PHP's built-in function number_format

查看PHP的内置函数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, '.', '');
    }

#4


0  

read number_format

number_format($number, 2, '.', '');

#5


0  

$num = 0.00638835;

$avg = sscanf($num,"%f")[0] /100;

echo sprintf("%.10f", $avg);

result 0.0000638835

#1


1  

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.

在PHP.net上阅读更多内容。您不需要确定数字是否为整数 - 只要它是一个数字,它将被格式化为两个小数位。

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

如果您想要千位分隔符,请将最后一个参数更改为“,”。

#2


2  

You can also use printf or sprintf

您也可以使用printf或sprintf

printf("%01.2f", '34.77');
$formatted_num = sprintf("%01.2f", '34.77');

#3


1  

Check out PHP's built-in function number_format

查看PHP的内置函数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, '.', '');
    }

#4


0  

read number_format

number_format($number, 2, '.', '');

#5


0  

$num = 0.00638835;

$avg = sscanf($num,"%f")[0] /100;

echo sprintf("%.10f", $avg);

result 0.0000638835