如何舍入到最接近的千位? [英] How to round to nearest Thousand?

查看:82
本文介绍了如何舍入到最接近的千位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数字四舍五入到最接近的千位?

How Do I round a number to its nearest thousand?

function round($var) {
    // Round it
}

推荐答案

PHP允许round的负精度,例如:

PHP allows negative precision for round such as with:

$x = round ($x, -3); // Uses default mode of PHP_ROUND_HALF_UP.

正精度表示在小数点后 处四舍五入,而负精度表示在小数点前 处具有相同的功效.所以:

Whereas a positive precision indicates where to round after the decimal point, negative precisions provide the same power before the decimal point. So:

n    round(1111.1111,n)
==   ==================
 3   1111.111
 2   1111.11
 1   1111.1
 0   1111
-1   1110
-2   1100
-3   1000

作为一般解决方案,即使对于没有内置语言的语言,您也可以执行以下操作:

As a general solution, even for languages that don't have it built in, you simply do something like:

  • 添加500.
  • 将其除以1000(并在必要时截断为整数).
  • 乘以1000.
  • add 500.
  • divide it by 1000 (and truncate to integer if necessary).
  • multiply by 1000.

当然,这是假设您想要 PHP_ROUND_HALF_UP行为.有些人认为银行家四舍五入对于减少累积误差更好,但这是另一个问题.

This is, of course, assuming you want the PHP_ROUND_HALF_UP behaviour. There are some who think that bankers rounding, PHP_ROUND_HALF_EVEN, is better for reducing cumulative errors but that's a topic for a different question.

这篇关于如何舍入到最接近的千位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆