[英]How to round a decimal amount, in c sharp, to a nearest fractional value given by users?
要求
用戶通常可以選擇小數值。 例如 0.5、0.01、0.33 或 0.1。
金額例如為 12.46,四舍五入規則為 0.01。
我不確定我是否解釋正確。
任何答案都非常感謝。 Khankooouuu 提前。
public class Test
{
static double round(double what, double to)
{
return to * Math.Round(what/to);
}
public static void Main()
{
Console.WriteLine(round(3.5, 1));
Console.WriteLine(round(3.44, 1));
Console.WriteLine(round(3.44, 0.1));
Console.WriteLine(round(1.68, 0.33));
Console.WriteLine(round(1.59, 0.33));
}
}
輸出
4
3
3.4
1.65
1.65
您可以使用 Decimal.Round() 方法對小數進行四舍五入,該方法具有 Decimal 的重載和 integer 的小數位數。 見這里。
至於查看用戶在輸入十進制值時想要使用多少位小數的部分,您可以將其轉換為字符串並計算小數點后的字符:
decimal UserDecimal;
string UserString = UserDecimal.ToString();
int DecimalPlaces = UserString.SubString(UserString.IndexOf(".")).Length;
最后,DecimalPlaces 將是用戶使用輸入的十進制值隱式請求的小數位數。
這就是你要找的??
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.