there is a strange behaviour double parse string input?

戏子无情 提交于 2019-12-29 09:19:10

问题


i try to read some excel file and converting some string column to save in db. BUT i face to face some double parse error: double result = double.Parse( 1,15); result: 1.149999999999.... i dont want to see this. i want double result = double.Parse( 1,15); result = 1.15


 static void Main(string[] args)
        {
            NumberStyles styles;
            IFormatProvider provider;

            styles = NumberStyles.Float;
            provider = CultureInfo.CreateSpecificCulture("tr-TR");

            string test = "1,15";
            double result = double.Parse(test, styles, CultureInfo.CreateSpecificCulture("tr-TR"));
            Console.WriteLine(result.ToString());
        }
    }

回答1:


Use the decimal data type for DB and Application if you need the high precision data types.




回答2:


You parse as a float, but convert to double -- float isn't accurate, hence why you're seeing the error.

Your code should be:

double result = double.Parse(...);

and not:

double result = float.Parse(...);

Edit:

Side note: When you convert something to a string, use value.ToString("R") if you want a round-trip to occur; that would represent the exact value as a string, not a truncated value.




回答3:


looks like error in the code: double result = float.Parse(); double.parse() should work fine.



来源:https://stackoverflow.com/questions/4569164/there-is-a-strange-behaviour-double-parse-string-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!