四舍五入到 25、50、75、100
Round to 25, 50, 75, 100
我不是数学家,所以我很难想出一个计算方法将小数点四舍五入为 25、50、75 和 100。这不是典型的四舍五入,因为decimals不会减少只会增加
示例:
如果是 11.12,四舍五入到 11.25
如果 11.34,四舍五入为 11.50
如果 11.52,四舍五入为 11.75
如果 11.76,四舍五入到 12.00
这是我的开始方法:
public float RoundNearestCents(String price)
{
float srp;
return srp;
}
我会使用这样的东西:
float RoundNearestCents(float price)
{
price*=(100/25.0); // now fractions are going away
if (price-floor(price)>=0.5) price++; // round up if fraction above 0.5
return floor(price)*(25.0/100.0); // cut of the fraction and restore original range
}
这是一种方式:
public decimal RoundNearestCents(decimal price)
{
decimal srp = price * 100;
decimal m = srp % 25;
srp = srp - m + (m > 0 ? 25 : 0);
return srp / 100;
}
public float RoundNearestCents(double d)
{
return (double)(Math.Ceiling(d * 4)) / 4;
}
我的代码可能不是最好的,但它会工作。
在你的函数中创建一个 float 和一个 int 像这样。
public float RoundNearestCents(String price)
{
float srp = float.Parse(price);
int srp1 = Int32.Parse(price);
if((srp-srp1)>=0.5)
srp1++;
else
return srp1;
return srp1;
}
int 会截去小数部分,这就像底价。
我建议使用没有浮点数的类型。
decimal RoundNearestCents(decimal price) {
// no problems with floating point as all calculations are exact
return Math.Floor((price * 100 + 24) / 25) * 25 / 100;
}
-- Why is your price string?
-- Because it's coming from a textbox.
我假设您的文本框应该支持将您的输入限制为最多保留 2 位小数的十进制数字。所以它的值已经是 decimal
了。但是我不知道你的申请类型是什么。如果你仍然想接受 string
然后考虑使用 decimal.TryParse
方法将其转换为 decimal
.
我不是数学家,所以我很难想出一个计算方法将小数点四舍五入为 25、50、75 和 100。这不是典型的四舍五入,因为decimals不会减少只会增加
示例:
如果是 11.12,四舍五入到 11.25
如果 11.34,四舍五入为 11.50
如果 11.52,四舍五入为 11.75
如果 11.76,四舍五入到 12.00
这是我的开始方法:
public float RoundNearestCents(String price)
{
float srp;
return srp;
}
我会使用这样的东西:
float RoundNearestCents(float price)
{
price*=(100/25.0); // now fractions are going away
if (price-floor(price)>=0.5) price++; // round up if fraction above 0.5
return floor(price)*(25.0/100.0); // cut of the fraction and restore original range
}
这是一种方式:
public decimal RoundNearestCents(decimal price)
{
decimal srp = price * 100;
decimal m = srp % 25;
srp = srp - m + (m > 0 ? 25 : 0);
return srp / 100;
}
public float RoundNearestCents(double d)
{
return (double)(Math.Ceiling(d * 4)) / 4;
}
我的代码可能不是最好的,但它会工作。 在你的函数中创建一个 float 和一个 int 像这样。
public float RoundNearestCents(String price)
{
float srp = float.Parse(price);
int srp1 = Int32.Parse(price);
if((srp-srp1)>=0.5)
srp1++;
else
return srp1;
return srp1;
}
int 会截去小数部分,这就像底价。
我建议使用没有浮点数的类型。
decimal RoundNearestCents(decimal price) {
// no problems with floating point as all calculations are exact
return Math.Floor((price * 100 + 24) / 25) * 25 / 100;
}
-- Why is your price string?
-- Because it's coming from a textbox.
我假设您的文本框应该支持将您的输入限制为最多保留 2 位小数的十进制数字。所以它的值已经是 decimal
了。但是我不知道你的申请类型是什么。如果你仍然想接受 string
然后考虑使用 decimal.TryParse
方法将其转换为 decimal
.