本文介绍了PHP - number_format 问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

number_format stupidly 默认对数字进行四舍五入.有没有一种简单的方法可以关闭舍入?我正在处理随机生成的数字,我可以得到类似...

number_format stupidly rounds numbers by default. Is there just a simple way to turn off the rounding? I'm working with randomly generated numbers, and I could get things like...

42533 * .003 = 127.599 或,
42533 * .03 = 1275.99 或,
42533 * .3 = 12759.9

42533 * .003 = 127.599 or,
42533 * .03 = 1275.99 or,
42533 * .3 = 12759.9

我需要 number_format(或其他格式)以传统的美国格式(用逗号分隔千位)表示结果,并且四舍五入.

I need number_format (or something else) to express the result in traditional U.S. format (with a comma separating the thousands) and not round the decimal.

有什么想法吗?

推荐答案

number_format 的第二个参数是数字中的小数位数.找出答案的最简单方法可能是将其视为字符串(根据 this question).传统的美国格式是默认行为,因此您无需指定其余参数.

The second argument of number_format is the number of decimals in the number. The easiest way to find that out is probably to treat it as a string (as per this question). Traditional US format is default behaviour, so you don't need to specify remaining arguments.

$num_decimals = strlen(substr(strrchr($number, "."), 1));
$formatted_number = number_format($number, $num_decimals);

这篇关于PHP - number_format 问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 03:37