Archived

This topic is now archived and is closed to further replies.

Telamon

C# - Converting a double to a string with limited precision

Recommended Posts

Ok. Really I''m embarassed to even have to ask, and I definately went through the docs to try to avoid it... If I have a double d = 2.0/9.0, I get a really nasty fraction. I want to convert this double to a string, but only keep the first two decimals. If I were coding in C, I''d simply sprintf with "%.2g", but I don''t know how to do this manipulation in C# the Right Way. Of course there is the hack where you multiply by 100, cast to int, and divide it back - but that''s really ugly. Please educate me! ---------------------------------------- Let be be finale of seem, seems to me. ---------------------------------------- Coding: http://www.stanford.edu/~jjshed/coding Miscellany: http://www.stanford.edu/~jjshed

Share this post


Link to post
Share on other sites
Would that be a string formatting class? Or the weird new C# string format specifiers (why did they change from C/C++?)? What is the sprintf equivalent in C#?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
d.ToString("0.00";

or, if it''s specifically money,

d.ToString("C";

Share this post


Link to post
Share on other sites