英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论