[英]Show decimal point number in PHP
I hold decimals in a database using DECIMAL(10,5) 我使用DECIMAL(10,5)在数据库中保留小数
I would like to format these numbers according to a few rules: 我想根据一些规则来格式化这些数字:
Here are some examples: 这里有些例子:
0.00000 => 0
0.51231 => 0.51231
0.12000 => 0.12
0.40000 => 0.40
0.67800 => 0.678
12.10000 => 12.10
Well here's one way (I haven't tested it yet so there may be minor errors): 好吧,这是一种方法(我尚未测试过,因此可能会有小错误):
$pattern = '/([0-9]+)\\.{0,1}([0-9]*?)0*$/';
$subject = 12.10000;
$matches = array();
$result = preg_match ($pattern, $subject, $matches);
$number = $matches[1];
if ($matches[2] != 0) {
$number .= '.'.$matches[2];
if ($matches[2] < 10) {
$number .= '0';
}
}
echo $number;
And here's another way (probably a little faster): 这是另一种方式(可能快一点):
$x = 1.000;
$result = (int)$x;
$trimmed = rtrim($x, 0);
if ($trimmed[strlen($trimmed) - 1] != '.') {
if ($trimmed[strlen($trimmed) - 2] == '.') {
$result = $trimmed.'0';
} else {
$result = $trimmed;
}
}
echo $result;
I know this is an old question, but the following quick function I wrote for my own project might help someone looking for this. 我知道这是一个老问题,但是我为自己的项目编写的以下快速功能可能会帮助寻找此问题的人。
function number_format_least_dp($number, $decimal_point = '.', $thousand_seperator = ','){
if (floatval($number) == (int)$number){
$number = number_format($number, 0, $decimal_point, $thousand_seperator);
} else {
$number = rtrim($number, '.0');
$number = number_format($number, strlen(substr(strrchr($number, '.'), 1)), $decimal_point, $thousand_seperator);
}
return $number;
}
I would utilize the number_format function in php to actually do the formatting after you determine the amount of decimal places to the number has. 确定数字的小数位数后,我将利用php中的number_format函数实际进行格式化。
Source: http://php.net/manual/en/function.number-format.php 来源: http : //php.net/manual/en/function.number-format.php
Example Usage: 用法示例:
$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 separator
$english_format_number = number_format($number, 2, '.', '');
// 1234.57
I haven't used it myself, but theres the NumberFormatter class: http://php.net/manual/class.numberformatter.php as part of the Internationalization Functions for this stuff. 我自己还没有使用过它,但是这里有NumberFormatter类: http : //php.net/manual/class.numberformatter.php作为该材料国际化功能的一部分。 Using that is a little more involved i think though. 我认为虽然使用起来有点复杂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.