Convert double to string keeping the same format

1

I need to convert a value of type double to string in C #, without this value being changed to scientific notation.

My code is:

double valor1 = 0.000024746578864525161;

string resultado = Convert.toString(valor1);

My output is: 2,8192381923E-15

I wanted the output to be exactly the same as in string

Output: "0.000024746578864525161";

The reasons why I need not to be expressed in scientific notation are:

1 - I'm reading an XLSX.

2 - I am doing the validation of the values entered by the user. And in this validation, I can not allow invalid characters.

3 - My string is submitted to a Regex.

Regex(@"[;!*#&@?()'$~^<>ºª%\{}A-Za-z]");

4 - The fact that my Regex does not accept characters causes the number expressed in 2,8192381923E-15 notation to become invalid.

There is a way to do the conversion of:

 double varlor = 0.000024746578864525161;

for

string resultado = "0.000024746578864525161"

and not for scientific notation:

string resultado = "2,8192381923E-15"
    
asked by anonymous 15.06.2018 / 15:01

1 answer

3

It's not possible to do just that, but something close, it can look like this:

valor1.ToString("#########0.000000000000000000000000")

You will notice that you do not get all the digits you can, no matter how many houses you put. The double type has limited accuracy. If you want more accuracy you should use a decimal . It can for 339 houses, I do not know why to do this, and it will not have more exact result. Take the test and you'll see it goes to 0.0000247465788645252 .

If you want greater precision then you should give up accuracy and scientific notation is appropriate.

Excel works well with scientific notation. If this is not what you want, the problem seems to be another.

Do not confuse the number with numeric representation. When you convert to string you are leaving the number and taking its representation, which are different things.

Of course, you can do a manual conversion, but it's a lot of work and not easy to do right.

Maybe I wanted to do something else, but we can not know the question. If the concept is wrong any technical answer will be bad.

    
15.06.2018 / 16:03