如何将阿拉伯数字转换为int?
我在C#中处理一个需要使用阿拉伯数字的项目,但是它必须在数据库中存储为整数,我需要一个解决方案来将阿拉伯数字转换为C#中的int。 有任何解决方案或帮助吗? 提前致谢
来自评论:
我有阿拉伯数字,如1,2,3,4 …并且必须转换为1,2,3,或234转换为234
使用此方法
private string toEnglishNumber(string input) { string EnglishNumbers = ""; for (int i = 0; i < input.Length; i++) { if (Char.IsDigit(input[i])) { EnglishNumbers += char.GetNumericValue(input, i); } else { EnglishNumbers += input[i].ToString(); } } return EnglishNumbers; }
像unicode中的1,2,3,4这样的阿拉伯数字被编码为1632到1641范围内的字符。从每个阿拉伯数字字符的unicode值中减去阿拉伯语零 (1632)的unicode以获得它们的数字值。 将每个数字值与其位值相乘,并将结果相加以得到整数。
或者使用Regex.Replace
将带有阿拉伯数字的字符串转换为带有十进制数字的字符串,然后使用Int.Parse
将结果转换为整数。
将阿拉伯数字转换为整数的简单方法
string EnglishNumbers=""; for (int i = 0; i < arabicnumbers.Length; i++) { EnglishNumbers += char.GetNumericValue(arabicnumbers, i); } int convertednumber=Convert.ToInt32(EnglishNumbers);
不幸的是,通过传入适当的IFormatProvider
(可能在即将发布的版本中)来解析完整的字符串表示是不可能的。 但是, char
类型具有GetNumericValue
方法,该方法将任何数字Unicode字符转换为double。 例如:
double two = char.GetNumericValue('٢'); Console.WriteLine(two); // prints 2
您可以使用它一次转换一个数字。
得到一个数字的值,从中减去零字符,例如正常数字, '1'-'0' = 1
, '2'-'0' = 2
。 等等
对于多位数,你可以使用这样的东西
result =0; foreach(char digit in number) { result *= 10; //shift the digit, multiply by ten for each shift result += (digit - '0)'; //add the int value of the current digit. }
如果您的号码使用阿拉伯字符,只需将’0’替换为阿拉伯语零。 这适用于任何数字符号,只要该符号系统中的0-9连续编码即可。
我知道这个问题有点陈旧,但是我在我的一个项目中遇到了类似的情况并且通过了这个问题并决定分享我的解决方案,这对我来说非常有效,并且希望它能为其他人服务。
private string ConvertToWesternArbicNumerals(string input) { var result = new StringBuilder(input.Length); foreach (char c in input.ToCharArray()) { //Check if the characters is recognized as UNICODE numeric value if yes if (char.IsNumber(c)) { // using char.GetNumericValue() convert numeric Unicode to a double-precision // floating point number (returns the numeric value of the passed char) // apend to final string holder result.Append(char.GetNumericValue(c)); } else { // apend non numeric chars to recreate the orignal string with the converted numbers result.Append(c); } } return result.ToString(); }
现在您只需调用该函数即可返回西方阿拉伯数字。
上述就是C#学习教程:如何将阿拉伯数字转换为int?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1000602.html