c# – 双精度数据类型,小数位后计数小数
下面的方法应该回答“小数精度,尾随数量的数量,这个(双重)值有什么?”.当值看起来像5900.43,5900.043等时,我做对了.当方法收到5900.00时,它返回0,这是错误的(在我的需要).
/// <summary> /// Return count of decimals after decimal-place /// </summary> private int getDecimalCount(double val) { int count = 0; ... return count; } 参数’val’是(此方法的正常值的样本) 5900.00返回2 我的问题是计算.0 .00 .000等等 题: [EDITED] 解决方法
编辑:更新以简化处理不同文化.
与@Miguel类似,这是我将如何处理它: public static int getDecimalCount(double dVal,string sVal,string culture) { CultureInfo info = CultureInfo.GetCultureInfo(culture); //Get the double value of the string representation,keeping culture in mind double test = Convert.ToDouble(sVal,info); //Get the decimal separator the specified culture char[] sep = info.NumberFormat.NumberDecimalSeparator.ToCharArray(); //Check to see if the culture-adjusted string is equal to the double if (dVal != test) { //The string conversion isn't correct,so throw an exception throw new System.ArgumentException("dVal doesn't equal sVal for the specified culture"); } //Split the string on the separator string[] segments = sVal.Split(sep); switch (segments.Length) { //Only one segment,so there was not fractional value - return 0 case 1: return 0; //Two segments,so return the length of the second segment case 2: return segments[1].Length; //More than two segments means it's invalid,so throw an exception default: throw new Exception("Something bad happened!"); } } 美国英语的快捷方法: public static int getDecimalCount(double dVal,string sVal) { return getDecimalCount(dVal,sVal,"en-US"); } 测试: static void Main(string[] args) { int i = 0; double d = 5900.00; string s = "5900.00"; Console.WriteLine("Testing with dVal = {0} and sVal = {1}.",d,s); i = getDecimalCount(d,s); Console.WriteLine("Expected output: 2. Actual output: {0}",i); Console.WriteLine(); d = 5900.09; s = "5900.09"; Console.WriteLine("Testing with dVal = {0} and sVal = {1}.",i); Console.WriteLine(); d = 5900.000; s = "5900.000"; Console.WriteLine("Testing with dVal = {0} and sVal = {1}.",s); Console.WriteLine("Expected output: 3. Actual output: {0}",i); Console.WriteLine(); d = 5900.001; s = "5900.001"; Console.WriteLine("Testing with dVal = {0} and sVal = {1}.",i); Console.WriteLine(); d = 1.0; s = "1.0"; Console.WriteLine("Testing with dVal = {0} and sVal = {1}.",s); Console.WriteLine("Expected output: 1. Actual output: {0}",i); Console.WriteLine(); d = 0.0000005; s = "0.0000005"; Console.WriteLine("Testing with dVal = {0} and sVal = {1}.",s); Console.WriteLine("Expected output: 7. Actual output: {0}",i); Console.WriteLine(); d = 1.0000000; s = "1.0000000"; Console.WriteLine("Testing with dVal = {0} and sVal = {1}.",i); Console.WriteLine(); d = 5900822; s = "5900822"; Console.WriteLine("Testing with dVal = {0} and sVal = {1}.",s); Console.WriteLine("Expected output: 0. Actual output: {0}",i); Console.ReadLine(); } 最后,测试的输出:
如果您对此有疑问或者没有意义,请告诉我. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |