riketscience
riketscience

Reputation: 198

Remove leading zeros from exponent when converting ToString

Let's say I have a double n = 0.00000123456

In one case I may want to show 1 decimal place n.ToString("E1") => "1.2E-006"

In another case I may want to show 4 decimal places n.ToString("E4") => "1.2346E-006"

But I don't want the leading zeros on the exponents, these numbers are for an axis where there is limited space.

I would like to see "1.2E-6" and "1.2346E-6" : nice - no leading zeros!

I read how can I remove zeros from exponent notation and I see I can use n.ToString("0.0E+0") and n.ToString("0.0000E+0") respectively.

That's great, but, given that I have an integer variable requiredDecimalPlaces telling me the number of decimal places I require at any time, would I have to create this format string with a loop, adding zeros each time?! That seems hacky. If this is the way to do it could somebody let me know? But like I said, converting my variable requiredDecimalPlaces (value 4 let's say) to a string "0.0000" and then appending "E+0" to the end in order to create "0.0000E+0" seems over-complicated.

Upvotes: 2

Views: 878

Answers (1)

juharr
juharr

Reputation: 32296

There isn't a standard numeric format that will do that so you'll have to create a custom one. And the easiest way to create that format would be the following.

number.ToString("0." + new string('0', decimalPlaces) + "E+0");

Upvotes: 1

Related Questions