BigDecimal setScale和round [英] BigDecimal setScale and round

查看:305
本文介绍了BigDecimal setScale和round的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个电话有什么区别? (有没有?)

What is the difference between this two call? (Is there any?)

// 1.
new BigDecimal("3.53456").round(new MathContext(4, RoundingMode.HALF_UP));
// 2.
new BigDecimal("3.53456").setScale(4, RoundingMode.HALF_UP);


推荐答案

提到但未直接解决的一个重点是precisionscale之间的区别以及它们在两个语句中的使用方式。 precision是数字中的有效数字总数。 scale是小数点右边的位数。

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

MathContext构造函数只接受precision和RoundingMode作为参数,并且因此,在第一个语句中永远不会指定scale。

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale()显然也接受scale作为参数作为RoundingMode,但是在第二个语句中从未指定精度。

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

如果将小数点向右移动一个位置,差异将变得清晰:

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

这篇关于BigDecimal setScale和round的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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