防止 number_format 舍入数字 - 添加逗号并保留小数点 - PHP
Prevent number_format from rounding numbers - add commas and keep the decimal point - PHP
数字格式添加我想要的逗号但删除小数点。
echo number_format("1000000.25");
这 return 1,000,000
我想要 return 1,000,000.25
我需要逗号和小数,没有任何数字舍入。我所有的值都是小数。它们长短不一。
我必须使用数字格式以外的格式吗?
如果你所说的 它们的长度不同 与小数部分有关,请看一下这段代码:
function getLen($var){
$tmp = explode('.', $var);
if(count($tmp)>1){
return strlen($tmp[1]);
}
}
$var = '1000000.255555'; // '1000000.25'; // '1000000';
echo number_format($var, getLen($var));
一些测试
1000000.255555
的输出:
1,000,000.255555
1000000.25
的输出:
1,000,000.25
1000000
的输出:
1,000,000
它计算 .
之后有多少个字符,并将其用作 number_format
函数中的参数;
否则就用常量代替函数调用。
以及一些参考...
string number_format ( float $number [, int $decimals = 0 ] )
你可以在描述中看到
number
The number being formatted.
decimals
Sets the number of decimal points.
还有一点:
[...]If two parameters are given, number will be formatted with decimals
decimals with a dot (".") in front, and a comma (",") between every
group of thousands.
number_format() 的文档表明第二个参数用于指定十进制:
echo number_format('1000000.25', 2);
$number = '1000000.25';
echo number_format($number, strlen(substr(strrchr($number, "."), 1)));
说明:
Number Format 采用第二个参数,它指定所需的小数位数,如 docs. This Stack overflow 答案中指出的那样告诉您如何获取提供的字符串的小数位数
数字格式添加我想要的逗号但删除小数点。
echo number_format("1000000.25");
这 return 1,000,000
我想要 return 1,000,000.25
我需要逗号和小数,没有任何数字舍入。我所有的值都是小数。它们长短不一。
我必须使用数字格式以外的格式吗?
如果你所说的 它们的长度不同 与小数部分有关,请看一下这段代码:
function getLen($var){
$tmp = explode('.', $var);
if(count($tmp)>1){
return strlen($tmp[1]);
}
}
$var = '1000000.255555'; // '1000000.25'; // '1000000';
echo number_format($var, getLen($var));
一些测试
1000000.255555
的输出:
1,000,000.255555
1000000.25
的输出:
1,000,000.25
1000000
的输出:
1,000,000
它计算 .
之后有多少个字符,并将其用作 number_format
函数中的参数;
否则就用常量代替函数调用。
以及一些参考...
string number_format ( float $number [, int $decimals = 0 ] )
你可以在描述中看到
number
The number being formatted.decimals
Sets the number of decimal points.
还有一点:
[...]If two parameters are given, number will be formatted with decimals decimals with a dot (".") in front, and a comma (",") between every group of thousands.
number_format() 的文档表明第二个参数用于指定十进制:
echo number_format('1000000.25', 2);
$number = '1000000.25';
echo number_format($number, strlen(substr(strrchr($number, "."), 1)));
说明: Number Format 采用第二个参数,它指定所需的小数位数,如 docs. This Stack overflow 答案中指出的那样告诉您如何获取提供的字符串的小数位数