Andy M
Andy M

Reputation: 6065

Double precision when number converted from string

I’m getting numbers from a database. Some are stored as double in the database and some are stored as string.

What I want to do is count the decimal number of caracters so : 345.34938 would give me a result of 5.

As I said, some of my double come from the database as double and some as string. I’m wondering if there could be any kind of problem when casting the string numbers to double, hence giving me wrong result when trying to count the decimals.

I think I should be ok but I’m afraid that in some situations I’ll end up receiving wrong double numbers when they’re casted from the string (thinking about having 1.9999999 instead of 2.0, things like that)...

Is there any kind of risk that casting my number from string to double would give me strange result when stored as double in my application ? Am I being to frisky around that ?

Upvotes: 1

Views: 397

Answers (1)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61952

Consider converting the string representations to System.Decimal with the decimal.Parse method. Because for a decimal there's a much better correspondence between the value of the number and its string representation. Also, it can handle more digits.

A System.Decimal will preserve trailing zeros present in the string (like "2.7500"), which a System.Double will not.

But if your strings never have more than 15 digits in total (including digits before the decimal point .), your approach with double will probably work. But the exact number represented almost always differs from "what you see" with a double, so the number of decimal figures is to be understood as what double.ToString() shows...

Maybe it's easier to just use the string directly, like

int numberOfDecimals = myString.Length - (myString.IndexOf('.') + 1);

Upvotes: 1

Related Questions