如何从十进制字符串中去掉零和小数点?
以下代码当前输出:
12.1
12.100
12.1000
12.00
12
12.0000
我怎样才能改变它,以便它输出:
12.1
12.1
12.1
12
12
12
Math.Round 似乎就是这样,但它让我定义了我想要的小数位数,但我希望它们如上所述是可变的。
如果没有数学方法可以做到这一点,我只会将字符串右侧的零和小数点去掉,但会认为有一种数学方法可以处理这个问题。
using System;
using System.Collections.Generic;
namespace Test8834234
{
public class Program
{
static void Main(string[] args)
{
List<string> decimalsAsStrings = new List<string>
{
"12.1",
"12.100",
"12.1000",
"12.00",
"12",
"12.0000"
};
foreach (var decimalAsString in decimalsAsStrings)
{
decimal dec = decimal.Parse(decimalAsString);
Console.WriteLine(dec);
}
Console.ReadLine();
}
}
}
The following code currently outputs:
12.1
12.100
12.1000
12.00
12
12.0000
How can I change it so it outputs:
12.1
12.1
12.1
12
12
12
Math.Round seems to be the thing, but it makes me define how many decimal places I want, but I want them to be variable as above.
If there is no mathematical way to do it, I'll just strip the zeros and decimal points off the right side of the strings, but would think there is a math way to handle this.
using System;
using System.Collections.Generic;
namespace Test8834234
{
public class Program
{
static void Main(string[] args)
{
List<string> decimalsAsStrings = new List<string>
{
"12.1",
"12.100",
"12.1000",
"12.00",
"12",
"12.0000"
};
foreach (var decimalAsString in decimalsAsStrings)
{
decimal dec = decimal.Parse(decimalAsString);
Console.WriteLine(dec);
}
Console.ReadLine();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您还可以将十进制的 ToString 与参数一起使用:
注意:您的代码可能存在国际化问题。按照您编码的方式,它将使用来自用户计算机的区域性信息,其中可能有
.
之外的其他内容作为小数分隔符。这可能会导致您的程序为使用.
作为千位分隔符的用户提供不正确的结果。如果您想保证解析方法始终表现相同,您可以使用 CultureInfo .不变文化。如果您确实想根据用户的区域性设置来解析字符串,那么您所做的就很好。
You can also use decimal's ToString with a parameter:
Note: You may have an internationalization issue with your code. The way you have coded it, it will use the culture info from the user's computer, which may have something other than
.
for the decimal separator. This might cause your program to give incorrect results for users that have.
for thousands separator.If you want to guarantee that the parse method will always behave the same, you could use CultureInfo.InvariantCulture. If you do actually want to parse the string according to the user's culture settings, what you are doing is fine.
使用:
从此处了解有关数字格式字符串的更多信息...
Use:
Learn more about numeric format strings from here...
此字符串格式应为您的一天:“0.##############################”。请记住,小数最多可以有 29 位有效数字。
示例:
This string format should make your day: "0.#############################". Keep in mind that decimals can have at most 29 significant digits though.
Examples: