there is a strange behaviour double parse string i

2019-01-29 05:52发布

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());
        }
    }

3条回答
甜甜的少女心
2楼-- · 2019-01-29 06:30

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

查看更多
霸刀☆藐视天下
3楼-- · 2019-01-29 06:39

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

查看更多
Root(大扎)
4楼-- · 2019-01-29 06:56

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.

查看更多
登录 后发表回答