c# - 如何在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。
解决方案
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(),但我不知道你的要求,所以我也包括在内
推荐阅读
- go - 制作切片大小
- python - `ImportError: No module named AppKit` 安装 AppKit 和 PyObjC 后
- matlab - 将多个概率图(使用 Matlab 中的 probplot )组合在一个图中,用于不同大小的数组
- sql-server - 在作业 SQL Server 中运行时 SSIS 失败
- sql-server - 在 SQL Server 中声明表变量问题
- python - 如何创建可以使用代码解锁的页面
- html - 空手道测试 - 如何在 Cucumber HTML 报告中嵌入 html?
- javascript - JavaScript - 在多个相同长度的对象数组中组合和添加值
- javascript - 提交表格不适用于新添加的使用 Javascript
- javascript - FullCalendar 从数据库填充事件