Converting Doubles to Strings

  • Thread starter Thread starter nvx
  • Start date Start date
N

nvx

Hi,
I'm looking for a simple way to convert a Double to a String exactly
the .ToString() does, except these two differences:
- the number of decimals is given (rounding is applied if
necessary), and
- trailing zeroes are kept.

This means I need it to be converted using the scientific notation if
the number is greater than a certain value etc., not just a simple
"this number of digits (or more if needed) before the decimal point
and precisely this number of decimals after the decimal point."

I could round the Double before converting it to a String
using .ToString(), but the trailing zeroes would be omitted.
Similarly, I could use the format string "0.00" or "0.00E+00", but the
scientific notation would not or would be used respectively (i.e.
converting 100.567 to "100.57" (which is OK) / "1.00E+02" (which means
a significant loss of data) and converting 123456789123456789.12345 to
"123456789123456789.12" (awful...) / 1.23E+15 (this is the correct
conversion now)).

So, do I need to create an appropriate format string according to the
current Double value or is there some elegant solution of this?

Thanks for any help...

With regards
nvx
 
You could make a separate function that takes in the double and
returns the string using your logic for if it is greater than a
certain value use the scientific notation if not use the other
formatting.

Or you could create a new class that inherits from double and
overrides the ToString method. This might be overkill though
depending on your exact situation.
 
Jeff said:
You could make a separate function that takes in the double and
returns the string using your logic for if it is greater than a
certain value use the scientific notation if not use the other
formatting.

Or you could create a new class that inherits from double and
overrides the ToString method. This might be overkill though
depending on your exact situation.

Overkill and/or impossible (double is a struct; structs are inherently
sealed).
 
Thanks both of you for your replies. It seems I'll have to code a bit
more...

With regards
nvx


Larry Lard napsal:
 
Back
Top