C#双 - toString()方法保留两位小数,但没有四舍五入格式 [英] C# Double - ToString() formatting with two decimal places but no rounding

查看:4880
本文介绍了C#双 - toString()方法保留两位小数,但没有四舍五入格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何在C#格式化双击字符串,以便只有两位小数?

How do I format a Double to a String in C# so as to have only two decimal places?

如果我用的String.Format({0:0.00}%,myDoubleValue)的数量是四舍五入,我想没有任何舍入一个简单的截断。我也想转换为字符串是文化的敏感。

If I use String.Format("{0:0.00}%", myDoubleValue) the number is then rounded and I want a simple truncate without any rounding. I also want the conversion to String to be culture sensitive.

推荐答案

我用下面的:

double x = Math.Truncate(myDoubleValue * 100) / 100;

例如:

如果数量为50.947563和您使用以下,则将发生以下情况:

If the number is 50.947563 and you use the following, the following will happen:

- Math.Truncate(50.947563 * 100) / 100;
- Math.Truncate(5094.7563) / 100;
- 5094 / 100
- 50.94

还有你的答案被截断,现在格式化字符串只需做到以下几点:

And there's your answer truncated, now to format the string simply do the following:

string s = string.Format("{0:N2}%", x); // No fear of rounding and takes the default number format

这篇关于C#双 - toString()方法保留两位小数,但没有四舍五入格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆