Formatting a double.ToString()

C

CJ

This is a really silly question, but I just can't get it right.

I have a double; the value is 0.00003025. I want to display it exactly
as it stands, but by default it is displayed in scientific notation.
I've tried specifying the format as "G", "R", "F", whatever; none of
them gives me the result I want. The closest is "N", but then I have
to specify the number of digits/decimals that I want to display, and
this may vary - now the value is 0.00003025, next time it may be 0.02
and then I don't want it to display as 0.02000000!
 
J

Jon Skeet [C# MVP]

CJ said:
This is a really silly question, but I just can't get it right.

I have a double; the value is 0.00003025. I want to display it exactly
as it stands, but by default it is displayed in scientific notation.
I've tried specifying the format as "G", "R", "F", whatever; none of
them gives me the result I want. The closest is "N", but then I have
to specify the number of digits/decimals that I want to display, and
this may vary - now the value is 0.00003025, next time it may be 0.02
and then I don't want it to display as 0.02000000!

The first thing you need to be aware of is that you *don't* have a
double with a value of 0.00003025. The closest you can have is a double
with a value of exactly
0.00003025000000000000006049848122469114741761586628854274749755859375.

Now, given that information, how do you know what you need to display?

I *suspect* that the round-trip format specifier ("R") would be what
you wanted in terms of precision - but that the scientific notation
part is where you get message up.

I'll think about it further, but I hope the above helps a bit...

Jon
 
C

CJ

Jon said:
The first thing you need to be aware of is that you *don't* have a
double with a value of 0.00003025. The closest you can have is a double
with a value of exactly
0.00003025000000000000006049848122469114741761586628854274749755859375.

Now, given that information, how do you know what you need to display?

I *suspect* that the round-trip format specifier ("R") would be what
you wanted in terms of precision - but that the scientific notation
part is where you get message up.

I'll think about it further, but I hope the above helps a bit...

Jon

Yeah, unfortunately I'm well aware of the problems with exact values of
floating point numbers. If I set a watch on the variable, though,
that's the value that it's showing me (it's the result of a
calculation). It's unlikely that there'll ever be such a small value
in the live environment, so I suspect I might just have to live with
the possibility that if there is, it'll be displayed in scientific
notation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top