我目前得到以下方法,它返回我的百分比值。例如,物品價格爲35萬美元,百分比爲7%,則返回24,500。檢查計算是否超過MaxValue
public static decimal GetPercentValue(decimal? percentage, decimal baseValue)
{
decimal result = 0m;
if (percentage != null)
{
try
{
result = Convert.ToDecimal(baseValue * percentage/100m);
}
catch (OverflowException)
{
result = 0;
Logger.Warn("OverflowException caught in GetPercentValue() - should better be handled UI-Sided!");
}
}
return result;
}
我不認爲這是正確的方式處理,那麼有沒有什麼辦法可以避免這種情況下的異常?
當用戶輸入像999,999,999,999,999,999
這樣的瘋狂號碼並計算其9999999999%
時,會引發OverflowException。這種方式我不能檢查percentage
或baseValue
<= decimal.MaxValue
只是因爲他們不是...計算結果本身然後超過小數範圍。
'我不認爲這是正確的方式處理 - - 你是什麼意思?目前還不清楚你認爲正確的方式應該是什麼樣的。 – Oded
如果你超過79228162514264337593543950335的最大值,你可能想重新考慮你的方法嗎? – coolmine
@Oded我認爲這應該(或可能)是可能的,而不需要通過簡單的if語句導致「OverflowException」的鉅額費用。 – SeToY