数字格式添加我想要的逗号但删除小数点。
echo number_format("1000000.25");
返回 1,000,000
我希望它返回 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.
关于php - 防止 number_format 舍入数字 - 添加逗号并保留小数点 - PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38105334/