I have a situation where I need to display a double value rounded to two decimal places, but displayed without the decimal. There will be some situations where I will want to use the same code and display the double value differently, so I was hoping I could handle this by passing in a string format pattern.
For example, the double value might be: 11367.2232
I want the value to be: 1136722
Another example, the value might be 344576.3457
I want the value to be 34457635
A third example, the value might be 546788
I want the value to be 54678800
So, I want to do something this:
String.Format("{PATTERN}", dblCurrency);
Is there any formatting pattern that would both round to 2 decimal places and strip the decimal from being displayed?
First, with (very) few exceptions, it’s generally bad idea to use
doublefor manipulating currency values. You should really usedecimalto represent such amounts.Second, rounding and display formatting are separate operations, and your code should express them separately.
string.Format()does not provide a single format mask that will do both, but you can easily achieve what you’re looking for:which will output:
The
D0format specifier emits numeric values without any separators and with no digits after the decimal point. You could also just useToString(), but I think the format specifier conveys the intent more clearly.