[英]Prevent number_format from rounding numbers - add commas and keep the decimal point - PHP
Number format adds the commas I want but removes the decimals. 数字格式添加我想要的逗号但删除小数。
echo number_format("1000000.25");
This returns 1,000,000 这将返回1,000,000
I want it to return 1,000,000.25 我希望它返回1,000,000.25
I need both the commas and the decimals, without any number rounding. 我需要逗号和小数,没有任何数字四舍五入。 All my values are decimals. 我的所有值都是小数。 They vary in length. 它们的长度各不相同。
Do I have to use something other than number format? 我是否必须使用数字格式以外的其他内容?
In case what you meant by they vary in length is related to the decimal part, take a look at this code: 如果你的意思是它们的长度不同与小数部分有关,请看一下这段代码:
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
: 输出为1000000.255555
: 1,000,000.255555 1,000,000.255555
Output for 1000000.25
: 输出为1000000.25
:
1,000,000.25 1,000,000.25
Output for 1000000
: 输出为1000000
:
1,000,000 百万
It counts how many chars there are after the .
它计算了之后有多少个字符.
and uses that as argument in the number_format
function; 并将其用作number_format
函数中的参数;
Otherwise just use a constant number instead of the function call. 否则只需使用常数而不是函数调用。
From the manual -> number_format() : 从手册 - > number_format() :
string number_format ( float $number [, int $decimals = 0 ] )
And you can see in the description that 你可以在描述中看到
number 数
The number being formatted. 正在格式化的数字。decimals 小数点
Sets the number of decimal points. 设置小数点数。
And a bit more: 还有一点:
[...]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 = '1000000.25';
echo number_format($number, strlen(substr(strrchr($number, "."), 1)));
Explanation : Number Format takes a second parameter which specifies the number of decimal places required as pointed out in the docs . 说明 :Number Format采用第二个参数,该参数指定文档中指出的所需小数位数。 This Stack overflow answer tells you how to get the number of decimal places of your provided string 此 Stack溢出答案告诉您如何获取所提供字符串的小数位数
The docs for number_format() indicate the second parameter is used to specify decimal: number_format()的文档指示第二个参数用于指定decimal:
echo number_format('1000000.25', 2);
Ref: http://php.net/manual/en/function.number-format.php 参考: http : //php.net/manual/en/function.number-format.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.