Convert double to string keeping the same format

Asked

Viewed 1,106 times

1

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

my code is:

double valor1 = 0.000024746578864525161;

string resultado = Convert.toString(valor1);

my way out is: 2,8192381923E-15

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

exit : "0.000024746578864525161";

the reasons why I need the value nay is expressed in scientific notation:

1 - I’m reading an XLSX.

2 - I am validating the values entered by the user. And in this validation, I cannot 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 notation 2,8192381923E-15 become invalid.

There is a way to make the conversion of:

 double varlor = 0.000024746578864525161;

for

string resultado = "0.000024746578864525161"

and not for scientific notation:

string resultado = "2,8192381923E-15"
  • What are the invalid characters? You may need to change your thinking and the logic of what you are trying to do!

  • Invalid characters are in Regex

  • Don’t want to edit this to show your real output in scientific notation? The nḿero Voce puts in the output example is not the same as in the variable "value1"

  • @Mik3i4a5 The answer solved your question? Do you think you can accept it? See [tour] if you don’t know how to do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site.

1 answer

3

It is not possible to do exactly like this, but something close, can form like this:

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

I put in the Github for future reference.

You’ll notice that it doesn’t take all the possible digits, no matter how many places. The type double has limited accuracy. If you want more accuracy you should use a decimal. You can put up 339 houses, I don’t know why you do this, and you won’t get a more accurate result. Take the test and you’ll see that it goes to 0.0000247465788645252.

If you want greater precision there you must give up the accuracy and the scientific notation is adequate.

Excel works well with scientific notation. If that’s not what you want, the problem seems to be another.

Do not confuse number with numerical representation. When convert to string is abandoning the number and taking its representation, which are different things.

Sure, you can do a manual conversion, but it’s a lot of work and it’s not easy to do right.

Maybe I wanted to do something else, but we have no way of knowing by the question. If the concept is wrong any technical answer will be bad.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.