[英]Format string with decimal
I am trying to take a string that may or may not contain a '.' 我正在尝试使用可能包含或可能不包含“。”的字符串。 to x amount of characters removing the "decimal point" as well.
到x个字符的数量也要删除“小数点”。 the result will ultimately be converted to a signed integer.
结果最终将转换为有符号整数。 I will also always need to the 1/10 decimal (ie 10 will become 100, 1 will become 10, etc...) I would like to just format the string without converting to an integer until the very end.
我也将始终需要1/10小数(即10将变成100,1将变成10,以此类推...)我想只格式化字符串,而不转换为整数,直到最后。
Example 例
if my incoming string is 如果我的传入字符串是
9.86 I want 98 as a string ( i don't care about rounding up or anything) 9.86我想要98作为字符串(我不在乎四舍五入)
if i get 9 I want 90 如果我得到9我想要90
if i get -100 i want -1000 如果我得到-100我想要-1000
if i get -95.353 i want -953 如果我得到-95.353我想要-953
string.Format("{0:d}", (int)9.015*10);
If you want a rounded result, replace the Cast 如果您想要四舍五入的结果,请替换演员表
Edit: But I missed the "string" part. 编辑:但是我错过了“字符串”部分。 Verbose code below
详细代码如下
var input = "9.86";
var len = input.IndexOf('.');
var result = "";
if (len > 0)
{
result = input.Substring(0, len);
result += input.Substring(len + 1, 1);
}
else
{
result = input + "0";
}
If you are essentially multiplying by ten the number contained in the string and dropping decimal places after the first, then you would be better off casting the string as a decimal and then doing the conversion and casting that number as an integer. 如果您实质上是将字符串中包含的数字乘以10并在第一个数字后保留小数位,那么最好将字符串强制转换为十进制,然后进行转换并将该数字强制转换为整数。 Otherwise you will have to write a large set of mathematical rules on how to modify your string based on a particular type of input.
否则,您将必须编写大量数学规则,以了解如何基于特定类型的输入来修改字符串。
string[] input = {"9.86", "9", "-100", "-95.3"};
List<int> intNums = new List<int>();
foreach (string s in input)
{
decimal number;
if (Decimal.TryParse(s, out number))
{
number = number * 10;
intNums.Add((int)number);
}
}
Output: [0] 98 int [1] 90 int [2] -1000 int [3] -953 int 输出:[0] 98 int [1] 90 int [2] -1000 int [3] -953 int
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.