php - 防止 number_format 舍入数字 - 添加逗号并保留小数点 - PHP

标签 php decimal number-formatting

数字格式添加我想要的逗号但删除小数点。

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 函数中的参数;

否则只需使用常量而不是函数调用。


还有一些引用...


来自manual -> 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/

相关文章:

php - 类似于 MySQLi 的 PDO 获取数组

php - array_key_exists 不工作

python-2.7 - 将一串数字转换为十六进制并返回到 dec pandas python

javascript - 在 javascript 或 jquery 中更改数字的逗号颜色

php - android将空行插入mysql

php - CakePHP:findById 返回不正确的行?

php - 如何在PHP中用加号前缀正数

r - 如何读取以逗号作为小数点分隔符的数字?

python - PyTorch 打印输出到 2dp

ruby - 我有一个像 30.6355 这样代表钱的数值,如何四舍五入到小数点后两位?