PHP 数字:小数点仅在需要时可见
我想知道是否存在一些函数可以按小数自动格式化数字,所以如果我有:
<?php
// $sql_result["col_number"] == 1,455.75
number_format ($sql_result["col_number"], 2, ".", "");
// will return 1455.75
// $sql_result["col_number"] == 1,455.00
number_format ($sql_result["col_number"], 2, ".", "");
// could I get 1455 instead of 1455.00?
?>
那么我的答案是,如果我的数据库中有 DECIMAL 数据格式(仅当它是圆形时),是否存在某种方法来删除小数?
或者我应该做类似的事情吗?
<?php
// $sql_result["col_number"] == 1,455.00
str_replace(".00", "", (string)number_format ($sql_result["col_number"], 2, ".", ""));
// will return 1455
?>
I'd like to know if exists some function to automatically format a number by it's decimal, so if I have:
<?php
// $sql_result["col_number"] == 1,455.75
number_format ($sql_result["col_number"], 2, ".", "");
// will return 1455.75
// $sql_result["col_number"] == 1,455.00
number_format ($sql_result["col_number"], 2, ".", "");
// could I get 1455 instead of 1455.00?
?>
so my answer is if does exist some way to remove the decimals if I have DECIMAL data forma in my DB only when it's round?
Or shoud I do something like that?
<?php
// $sql_result["col_number"] == 1,455.00
str_replace(".00", "", (string)number_format ($sql_result["col_number"], 2, ".", ""));
// will return 1455
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
floatval 或简单地转换为 float
floatval or simply casting to float
我实际上认为你的解决方法和任何方法一样好。简单明了,这里讨论性能确实没有意义,直接说吧。
I actually think that your workaround is as good as any. It's simple and clear, and there's really no point talking about performance here, so just go for it.
正如埃米尔所说,你的很好。但如果您也想从
7.50
中删除0
,我有一个建议,rtrim()
:As Emil says yours are good. But if you want to remove
0
from e.g.7.50
too, I've got a suggestion,rtrim()
:如果您可能想保留一位小数但不想保留多余的零,您还可以使用 rtrim(),它会删除多余的 0。 (例如,4.50 变为 4.5。)还允许您将小数位数从 2 更改为任何其他数字。
You could also use rtrim(), which would remove excess 0s, in the case where you might want to keep one decimal place but not the excess zeros. (For example, 4.50 becomes 4.5.) Also allows you to change the number of decimal places from 2 to any other number.
实际上,我认为对于刚刚搜索此类内容的人来说,我能想到的最干净的方法就是这样做:
Actually I think the cleanest way I can think of to do this for someone that just did a search looking for this sort of thing is to do this:
我被指责做了这样的事情:
I've been accused of doing something like this:
如果您的目标是美元,我喜欢使用这种方法:
If you are targeting US currency I like to use this method:
我的,因为大多数数量或件数不需要小数,所以此功能只会在需要时显示小数。
Mine since most quantity or pieces do not require decimal, this function will only show decimal when needed.
沃伦的回答帮助了我。我不需要 number_format 函数,所以我只是这样做了
但在OP的情况下,他需要 number_format 来删除逗号。所以这对他有用
Warren.S answer helped me out. I didn't need the number_format function, so I just did this
But in the OP's case, he needs number_format to remove the commas. So this would work for him
由于我找不到灵活的解决方案,我编写了一个简单的函数来获得最佳结果:
Since I could not find a flexible solution I wrote a simple function to get the best result:
怎么样
What about