获得不同的结果Math.Round [英] Getting different result in Math.Round

查看:147
本文介绍了获得不同的结果Math.Round的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ticketPriceInPence = 7360
percentageToRefund = 100

(int)(Math.Round((ticketPriceInPence * 0.01) * (percentageToRefund * 0.01), 2, MidpointRounding.AwayFromZero) * 100)

这导致:73.59

(int)(Math.Round((ticketPriceInPence * 0.01) * (percentageToRefund * 0.01) * 100, 2, MidpointRounding.AwayFromZero))

这导致:73.60

任何想法,为什么它会导致不同的2种不同的结果。

Any idea why it results in different 2 different results

推荐答案

这是的重新$ P的>旧的情况下 $ psent小数正是。

It's the old case of floating point numbers not being able to represent decimals exactly.

您似乎与金钱打交道这里,然后你真的应该考虑使用的小数

You seem to be dealing with money here and then you really should consider using decimal.

decimal ticketPriceInPence = 7360;
decimal percentageToRefund = 100;
var result1 = (int)(Math.Round((ticketPriceInPence * 0.01m) * (percentageToRefund * 0.01m), 2, MidpointRounding.AwayFromZero) * 100);
var result2 = (int)(Math.Round((ticketPriceInPence * 0.01m) * (percentageToRefund * 0.01m) * 100, 2, MidpointRounding.AwayFromZero));

这篇关于获得不同的结果Math.Round的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆