简体   繁体   English

试图限制BigDecimal除法Java的小数位数

[英]Trying to limit number of decimal places for BigDecimal division Java

I am new to the Java world and am trying to learn how to use BigDecimal. 我是Java世界的新手,正在尝试学习如何使用BigDecimal。 What I am trying to do now is limit the number of decimal places in a division problem. 我现在想做的是限制除法问题中的小数位数。 My line of code is: 我的代码行是:

quotient=one.divide(x);

Where quotient, one and x are all of type BigDecimal. 在商中,one和x均为BigDecimal类型。 I cannot figure out, however, how to limit the number of decimal places to print out, saying that x is some large number, and one is equal to 1. All help is appreciated, thanks! 但是,我不知道如何限制要打印的小数位数,即x是一个大数字,一个等于1。感谢所有帮助,谢谢!

That code will die a horrible death if the division has a non-terminating decimal expansion. 如果该除法器具有无终止的十进制扩展名,那么该代码将死得很惨。 See javadoc of divide(BigDecimal divisor) : 请参阅divide(BigDecimal divisor) javadoc divide(BigDecimal divisor)

if the exact quotient cannot be represented (because it has a non-terminating decimal expansion) an ArithmeticException is thrown. 如果无法表示确切的商(因为它具有无终止的十进制扩展),则抛出ArithmeticException

Example: 例:

BigDecimal one = BigDecimal.ONE;
BigDecimal x = BigDecimal.valueOf(7);
one.divide(x); // throws java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.

Use one of the other overloads of divide() , eg divide(BigDecimal divisor, int scale, RoundingMode roundingMode) : 使用divide()的其他重载之一,例如divide(BigDecimal divisor, int scale, RoundingMode roundingMode)

BigDecimal one = BigDecimal.ONE;
BigDecimal x = BigDecimal.valueOf(7);
BigDecimal quotient = one.divide(x, 5, RoundingMode.HALF_UP);
System.out.println(quotient); // prints: 0.14286
BigDecimal one = BigDecimal.ONE;
BigDecimal x = BigDecimal.valueOf(7);
BigDecimal quotient = one.divide(x, 30, RoundingMode.HALF_UP);
System.out.println(quotient); // prints: 0.142857142857142857142857142857

To set the number of decimal places in a variable BigDecimal you can use the following sentences depend that you want achieve 要设置变量BigDecimal中的小数位数,您可以根据需要实现以下语句

value = value.setScale(2, RoundingMode.CEILING) to do 'cut' the part after 2 decimals value = value.setScale(2, RoundingMode.CEILING)在2个小数点后进行“剪切”

or 要么

value = value.setScale(2, RoundingMode.HALF_UP) to do common round value = value.setScale(2, RoundingMode.HALF_UP)做普通的回合

See Rounding BigDecimal to *always* have two decimal places 请参见将BigDecimal舍入为*始终*具有两个小数位

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM