[英]How can I strip zeros and decimal points off of decimal strings?
以下代码目前输出:
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();
}
}
}
您还可以将decimal的ToString与参数一起使用:
string s = dec.ToString("0.#");
注意:您的代码可能存在国际化问题。 你编写它的方式,它将使用用户计算机的文化信息,这可能有其他东西.
用于小数分隔符。 这可能会导致您的程序为具有的用户提供不正确的结果.
千位分隔符。
如果要保证parse方法始终表现相同,可以使用CultureInfo.InvariantCulture 。 如果您确实想根据用户的文化设置解析字符串,那么您正在做的事情很好。
这种字符串格式应该是你的日子:“0。#############################”。 请记住,小数最多可以包含29位有效数字。
例子:
? (1000000.00000000000050000000000m).ToString("0.#############################")
-> 1000000.0000000000005
? (1000000.00000000000050000000001m).ToString("0.#############################")
-> 1000000.0000000000005
? (1000000.0000000000005000000001m).ToString("0.#############################")
-> 1000000.0000000000005000000001
? (9223372036854775807.0000000001m).ToString("0.#############################")
-> 9223372036854775807
? (9223372036854775807.000000001m).ToString("0.#############################")
-> 9223372036854775807.000000001
public static string RemoveDecimalsFromString(string input)
{
decimal IndexOfDot = input.IndexOf(".");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < IndexOfDot; i++)
{
sb.Append(input[i]);
}
return sb.ToString();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.