如何将字符串转换为具有3个小数位的小数? [英] How to convert string to decimal with 3 decimal places?

查看:74
本文介绍了如何将字符串转换为具有3个小数位的小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

string num = 23.6;

我想知道如何将其转换为具有3个小数位的小数喜欢

I want to know how can I convert it into decimal with 3 decimal places like

decimal nn = 23.600 

有什么方法吗?

推荐答案

我尽力了..

首先,您的 string num = 23.6; 不会 even 进行编译.您需要对字符串使用双引号,例如 string num ="23.6";

First of all your string num = 23.6; won't even compile. You need to use double quotes with your strings like string num = "23.6";

如果要以小数形式将其获取,则需要首先使用具有.作为IFormatProvider 对其进行解析.="https://msdn.microsoft.com/zh-cn/library/system.globalization.numberformatinfo.numberdecimalseparator.aspx" rel ="nofollow noreferrer"> NumberDecimalSeparator InvariantCulture (如果您的 CurrentCulture 已经使用.,则您不必必须通过第二个参数);

If you wanna get this as a decimal, you need to parse it first with a IFormatProvider that have . as a NumberDecimalSeparator like InvariantCulture(if your CurrentCulture uses . already, you don't have to pass second paramter);

decimal nn = decimal.Parse(num, CultureInfo.InvariantCulture);

现在我们有一个 23.6 作为十进制值.但是作为一个值, 23.6 23.60 23.600 23.60000000000 完全相同,对吗?无论将哪一个解析为十进制,您都将在调试器中获得与 23.6M 相同的值.看起来这些是 not true.请参阅Jon Skeet对此答案的评论以及 .NET中的十进制浮点的保持零"部分./a>文章.

Now we have a 23.6 as a decimal value. But as a value, 23.6, 23.60, 23.600 and 23.60000000000 are totally same, right? No matter which one you parse it to decimal, you will get the same value as a 23.6M in debugger. Looks like these are not true. See Jon Skeet comments on this answer and his "Keeping zeroes" section on Decimal floating point in .NET article.

现在呢?是的,我们需要将其文本表示形式表示为 23.600 .由于我们只需要文本表示形式中的小数点分隔符,因此格式说明符将满足需求.

Now what? Yes, we need to get it's textual representation as 23.600. Since we need only decimal separator in a textual representation, The "F" Format Specifier will fits out needs.

string str = nn.ToString("F3", CultureInfo.InvariantCulture); // 23.600

这篇关于如何将字符串转换为具有3个小数位的小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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