.Net: number.ToString without rounding

人盡茶涼 提交于 2019-12-13 08:15:26

问题


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


回答1:


 Console.Write(Math.Truncate(number * 100) / 100);

This should work. Read more answers here




回答2:


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



来源:https://stackoverflow.com/questions/33337453/net-number-tostring-without-rounding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!