Double转换为BigDecimal时,舍入不正确。

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

Double to BigDecimal rounding incorrectly

问题

以下是您的代码的翻译部分:

import java.math.RoundingMode

// 计算净价值的函数
fun fValueNettoBase(priceNetto: Double, quantity: Double) = dRound(priceNetto * quantity, 2)

// 对双精度数进行四舍五入
fun dRound(double: Double, nrOfDec: Int = 2): Double =
    double.toBigDecimal().setScale(nrOfDec, RoundingMode.HALF_UP).toDouble()

fun main() {
    val quantity = 1.38
    val price = 3.25
    println("${fValueNettoBase(price, quantity)}")
}

关于为什么会出现四舍五入错误的问题,可能与双精度浮点数到BigDecimal的转换有关,以及从BigDecimal再转回双精度浮点数的过程。您可能需要仔细检查这些转换的过程以确保精确性。

英文:

I have the following code:

import java.math.RoundingMode
fun fValueNettoBase(priceNetto:Double , quantity:Double) = dRound(priceNetto * quantity, 2)
fun dRound(double: Double, nrOfDec: Int = 2): Double =
    double.toBigDecimal().setScale(nrOfDec, RoundingMode.HALF_UP).toDouble()
fun main() {
    val quantity = 1.38
    val price = 3.25
	println("${fValueNettoBase(price,quantity)}")
}

it is rounded incorrectly to 4.48 instead of 4.49, any ideas why? My gut feel is it has to do with the conversion from double to big decimal and the other way round, but I'm not sure how to make it work

答案1

得分: 3

如果您希望此舍入正确工作,您必须始终在代码的每个阶段使用BigDecimal,绝不能使用Double。使用Double可能会引入小的正负偏差,导致舍入方向与您的预期不符。

英文:

If you want this rounding to work correctly, you must never, ever use Double. You must use BigDecimal at every stage of your code. Using Double can introduce a small +/- to your values that can cause rounding to go in a different direction than you expect.

huangapple
  • 本文由 发表于 2023年4月13日 15:45:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002880.html
匿名

发表评论

匿名网友

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

确定