如何在Java中为Math.Context设置精度?

huangapple go评论79阅读模式
英文:

How to set scale for Math.Context in Java?

问题

我在我的编码中使用了Math.Context。现在的问题是Math.Context会计算小数点后的所有内容。我想要为Math.Context定义一个小数点后8位的精度(即小数点后8位)。请注意,我不是在寻找精度。我知道如何定义精度。我需要的是小数点后的位数。

这是我的Math.Context代码行:

answer = firstvalue.multiply(secondvalue).divide(new BigDecimal("1240"), MathContext.DECIMAL32);
英文:

I'm using Math.Context in my coding. Now the problem is Math.Context is calculating everything after decimal. I want to define Scale of 8 (means 8 digits after decimal point) for Math.Context. Please note i'm not looking for precision. I know how to define precision. I need scale.

This is my Math.Context code line :

answer =  firstvalue.multiply(secondvalue).divide(new BigDecimal("1240"), MathContext.DECIMAL32);

答案1

得分: 0

构造函数或 MathContext 类中的辅助方法中没有设置标度的参数。您可以尝试使用 BigDecimal,其中可以指定标度。

在 divide 方法中,参数可以按如下方式传递:

BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode)

firstvalue.multiply(secondvalue).divide(new BigDecimal("1240"), 4, RoundingMode.FLOOR);

MathContext javadoc 参考链接:https://docs.oracle.com/javase/7/docs/api/java/math/MathContext.html

英文:

There is no argument in the constructor or helper method in MathContext class to set scale. you can try BigDecimal where scale can be given as

In divide argument the parameters can be passed as follows,

BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) i.e

firstvalue.multiply(secondvalue).divide(new BigDecimal("1240"), 4, RoundingMode.FLOOR);

Reference to MathContext javadoc: https://docs.oracle.com/javase/7/docs/api/java/math/MathContext.html

答案2

得分: 0

你可以做你所要求的事情。我会告诉你如何做,但在此之前,我想提醒你,你需要在BigDecimal上使用setScale()。在这种情况下,我假设answer变量是BigDecimal。以下是你的答案:

answer = firstvalue.multiply(secondvalue).divide(new BigDecimal("1240"), MathContext.DECIMAL32);
answer = answer.setScale(5, RoundingMode.HALF_EVEN);
// 你可以设置自己想要的精度或舍入模式

希望这对你有所帮助。

英文:

You can do what you're asking. I show you how but before that i would like to tell you that you have to setScale() on BigDecimal. In this case I'm assuming that answer variable is BigDecimal . Here is your answer

answer =  firstvalue.multiply(secondvalue).divide(new BigDecimal("1240"), MathContext.DECIMAL32);
answer = answer.setScale(5, RoundingMode.HALF_EVEN); 
// YOU CAN SET YOUR OWN DESIRED SCALE OR ROUNDINGMODE

huangapple
  • 本文由 发表于 2020年7月26日 17:39:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63098465.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定