【问题标题】:Getting a Quantity's value as a BigDecimal将 Quantity 的值作为 BigDecimal 获取
【发布时间】:2021-06-01 13:00:00
【问题描述】:

当需要从Quantity 中取回一个数字时,getValue() 返回一个Number,它可以转换为intdoublefloatlongshort。似乎很奇怪,没有办法将它作为BigDecimal。我错过了什么还是有充分的理由将其作为BigDecimal 获得?

【问题讨论】:

  • java.measure的实现在哪里?我想这是因为他们想使用原始值来保持一切快速和简单。 BigDecimal 方法可能会变得非常慢,因为它基本上可以是一个无限大的数字。
  • BigDecimalNumber 的子类,因此getValue() 可以返回BigDecimal。这取决于实施。至于为什么会这样,反过来想。如果您指定getValue() 始终返回BigDecimal,那么任何实现都不能返回任何不是BigDecimal 的东西。如果用浮点数描述某个数量更有意义怎么办?没有这个选项会很烦人。
  • @BenjaminM Quantity 的实现在 Indriya 模块中。其中之一是基于BigDecimal,这就是为什么我必须使用new BigDecimal(quantity.getValue().toString()) 才能让BigDecimal 退出似乎很奇怪。

标签: java units-of-measurement


【解决方案1】:

我看了https://github.com/unitsofmeasurement/indriya的代码

这是怎么回事:

  1. 调用Quantities.getQuantity(...) 返回new NumberQuantity

  2. NumberQuantity 构造函数调用Calculator.peek()

  3. peek 呼叫NumberSystem.narrow(...)

这是有趣的部分。方法文档说:

* 'Narrows' given {@code number} as a {@link Number} that best
* represents the numeric value within the set of number types this NumberSystem
* supports.
* <p>
* eg. A BigInteger that is within range of Java's {@code Long} type can be narrowed to
* Long w/o loss of precision.

DefaultNumberSystem.narrow 的代码(NumberSystem 接口的默认实现)向您展示了它是如何完成的。

换句话说:每次您创建Quantity 时,它都会缩小范围。当您查看其他NumberQuantity 方法时,您会发现这种情况一直在发生:当您运行addsubtract 等时,总会有一个peek 调用涉及,然后调用@987654341 @。

我想这样做是为了加快计算速度。因为使用原语比使用BigDecimalBigInteger 快很多。他们确保您不会失去精确度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多