.Net:number.ToString没有舍入 [英] .Net: number.ToString without rounding
问题描述
Dim number = 5.678
Console.WriteLine(number.ToString(#,## 0。##))
显示 5.68
。是否有任何数字格式的字符串没有四舍五入?
更新:所需的结果是 5.67
如果您总是需要截取2个位置,您可以使用:
pre > Console.WriteLine({0:F2},number - 0.005);
否则,您可以根据需要更改数字'0.005'。
更新:如果你想把它当作字符串,我不认为在C#中有任何现成的解决方案,所以你可能需要做一些额外的工作,如下(你可以创建一个辅助方法) :
const double number = 5.678; //输入数字
var split = number.ToString(CultureInfo.InvariantCulture).Split('。');
Console.WriteLine(split [0] +(split.Length> 1?。:)+(split.Length> 1?split [1] .Substring(0,split [1] 。长度> 1?2:split [1] .Length):));
输入:5.678;
输出:5.67;
输入:5.6325;
输出:5.63;
输入:5.64;
输出:5.64
输入:5.6;
输出:5.6;
输入:585.6138 $ b $输出:585.61
Dim number = 5.678
Console.WriteLine(number.ToString("#,##0.##"))
displays 5.68
. Is there any number format string without rounding it?
UPDATE: desired result is 5.67
If you always have to truncate till 2 places, you can use:
Console.WriteLine("{0:F2}", number - 0.005);
Otherwise you can change number '0.005' as per your need.
Update: If you want to treat this as string, I don't think there is any readymade solution in C#, so you might have to do some extra work like below(You can create a helper method):
const double number = 5.678; //input number
var split = number.ToString(CultureInfo.InvariantCulture).Split('.');
Console.WriteLine(split[0] + (split.Length > 1 ? "." : "") + (split.Length > 1 ? split[1].Substring(0, split[1].Length > 1 ? 2 : split[1].Length) : ""));
Input: 5.678; Output: 5.67;
Input: 5.6325; Output: 5.63;
Input: 5.64; Output: 5.64
Input: 5.6; Output: 5.6;
input: 585.6138 output: 585.61
这篇关于.Net:number.ToString没有舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!