删除小数点,转换为int [英] removing decimal, to an int
问题描述
嗨
我有尝试删除小数的这种方法
Hi
I got this method trying to remove decimal
public static int[] encode(String orig)
{
String int_part = " ";
String dec_part = " ";
Regex digitsOnly = new Regex(@"[^(\d|\.)]");
//orig = Regex.Replace(orig,"[^\\.0-8]", ""); //remove non-numerical characters
int dot_index = orig.Trim().IndexOf("0");
if (dot_index > 0)
{ //do we have a decimal place?
int_part = orig.Substring(0, dot_index); //get integer portion of string
dec_part = orig.Substring(dot_index); //get part after decimal
int_part = Regex.Replace(int_part, "^0+", ""); //remove leading 0's
dec_part = Regex.Replace(dec_part, "0+$", ""); //remove trailing 0's
int[] result = new int[2];
int.TryParse("0", out result[0]);
int.TryParse("1", out result[1]);
return result;
}
return new int[] { 0, 1 };
}
推荐答案
", ); // 删除尾随的0's int []结果= 新 int [ 2 ]; int .TryParse(" , 输出结果[ 0 ]); int .TryParse(" , 输出结果[ 1 ]); 返回结果; } 返回 新 int [] { 0 , 1 }; }
", ""); //remove trailing 0's int[] result = new int[2]; int.TryParse("0", out result[0]); int.TryParse("1", out result[1]); return result; } return new int[] { 0, 1 }; }
有一种比字符串处理更简单的方法:
There is a simpler way to do this than string manipulation:
- 删除数字的非数字部分,保留小数点.
- 使用 ^ ](或 Decimal.TryParse [ ^ ])将您的字符串转换为十进制
- 使用 Decimal.Truncate [ ^ ]到获取整数部分,其结果是小数,因此如果需要,您需要将其强制转换为int.您还可以使用 Math.Floor [
- Remove the non-numeric part of the number, preserving the decimal point.
- Use Decimal.Parse[^] (or Decimal.TryParse[^]) to convert your string into a decimal
- Use Decimal.Truncate[^] to get the integer part, the result of this is a decimal, so you will need cast to int if needed. You could also use Math.Floor[^] if you want
- Subtract the integer part from the original value & perform a
ToString()
. Stripping the leading "0." from this will give you the fractional part as a string
注意将小数部分存储为int可能会导致问题:
7.01-> int = 7,分数字符串="01"如果将01解析为一个int,则将得到1,因此您的数组将为7,1
7.1-> int = 7,分数字符串="1"如果将1解析为一个int,则将得到1,所以您的数组也将是7,1
实际上,我曾经是个白痴:一旦有了十进制"字符串,就可以在其上执行字符串 .split(''.''.''并解析生成的两个元素中的两个元素-element字符串数组:doh:
Note storing the fractional part as an int might cause problems:
7.01 --> int = 7, fratctional string = "01" if you parse 01 to an int, you''ll get 1 so your array would be 7,1
7.1 --> int = 7, fratctional string = "1" if you parse 1 to an int, you''ll get 1 so your array would be 7,1 also
Actualy I''ve been an idiot: once you have the "decimal" string, you can do a string .split(''.'') on it and parse the two elements in the resulting two-element array of string :doh:
不完全知道您遇到了什么问题,我想您想将Int转换为十进制值.因此,为什么不使用诸如convert或parse之类的inbuld方法,这可能对您有用.
谢谢,
Ambesha
Not exactly know that what problem you are getting , I think you want to convert your decimal value in Int. so why not you use inbuld method like convert or parse, that might be useful for you.
Thanks,
Ambesha
这篇关于删除小数点,转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!