首页 > 解决方案 > 如何在c#中有效地比较两个十进制值

问题描述

我在 Windows 窗体中发布了三个值。

Value A: 97.65
Value B: 2
Total: 195.6

我有一个检查总数是否不超过阈值的函数300000

public bool isValidAmount(decimal valA, int valB, decimal total) 
{
   int threshold = 300000;
   int calcTotalAmount = (int) Math.Ceiling(valA * valB);
   int totalToInt = (int) Math.Ceiling(total);
 
   if ((calcTotalAmount == totalToInt) && calcTotalAmount <= threshold) 
   {
      return true;
   }
   else if (calcTotalAmount != totalToInt) 
   {
      return false;
   }
   else if (calcTotalAmount > threshold) 
   {
      return false;
   }

}

我的问题是始终满足第一个条件,因为我的输入 Total 小于 300000。如何确保有效执行验证?请帮忙。

但是当你乘以 97.65 *2 = 195.3。

标签: c#

解决方案


var valueA = 1.0;
var valueB = 400000;
var total = 400000.0;
var check = isValidAmount((decimal)valueA, valueB, (decimal)total);

将参数传递给 isValidAmount() 方法时不要忘记转换为十进制

然后写你的方法如下,

public bool isValidAmount(decimal valA, int valB, decimal total) 
{
   var threshold = 300000;
   var calcTotalAmount = (int) Math.Ceiling(valA * valB);
   var totalToInt = (int) Math.Ceiling(total);

   if (calcTotalAmount == totalToInt && calcTotalAmount <= threshold) 
      return true;
   else
      return false;
}

你不需要 Math.Ceiling(),但我不知道你的要求,所以我也包括在内


推荐阅读