0

I need help converting a string to double with 7 decimals. I have a string "00000827700000" and need it converted to 82.77

Tried using String.Format() with {0:N7} without success.

3
  • 9
    Is the format always like that? With the stars, and the exact number of characters? Are you sure that double is the most appropriate type here, rather than decimal? Commented Jun 19, 2012 at 20:23
  • 2
    I've edited my answer based on the edited question. It would really help if you'd clarified this to start with - and answered the other questions posed in comments. Commented Jun 19, 2012 at 20:30
  • 1
    Welcome to StackOverflow! By the way, having Jon Skeet answer your first question is like having Eric Clapton walk up to you to help when you asked for someone to "teach you a couple chords". Please heed his advice. Commented Jun 19, 2012 at 20:46

2 Answers 2

7

It looks like you could use:

decimal x = decimal.Parse(text.Substring(0, 7) + "." +
                          text.Substring(7),
                          CultureInfo.InvariantCulture);

That would actually parse it to 82.7700000, as decimal preserves trailing zeroes (to an extent) but maybe that's good enough? It not, you could change the second argument to

text.Substring(7).TrimEnd('0')

Note that I'd strongly recommend you to at least consider using decimal instead of double. You haven't explained what this value represents, but if it's stored as decimal figures which you need to preserve, it smells more like a decimal to me.

Sign up to request clarification or add additional context in comments.

3 Comments

well, now I can't write it any clearer than you have done. I would still use TryParse, but other than that it wouldn't be any different. Actually, the second argument could just be text.Substring(7).TrimEnd('0') now since there is no garbage characters.
@Chad: I'd only use TryParse if it were legitimate for this to be bad data. I expect it's actually machine-generated, and I'd be happy with an exception being thrown here just as I would if (say) XML parsing failed. Good point on the Substring call though - editing...
fair enough, I actually thought of a potentially simpler way, see my edited response. Not sure which is quicker.
3

Based on the edit, it could be simplified as

var text = "00000827700000";
var x = decimal.Parse(text, CultureInfo.InvariantCulture) / 10000000;
Console.Write(String.Format("{0:N7}", x));

2 Comments

This is the best I can come up with, formats with 7 decimals showing, and converts the value to a proper decimal, rather than leaving it stringly typed
Yes, that's a good point - I had originally considered dividing, but it was a pain when the two pieces were separated. Now it's a very natural answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.