HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How do I display a decimal value to 2 decimal places?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howdisplayplacesdecimalvalue

Problem

When displaying the value of a decimal currently with .ToString(), it's accurate to like 15 decimal places, and since I'm using it to represent dollars and cents, I only want the output to be 2 decimal places.

Do I use a variation of .ToString() for this?

Solution

decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m


or

decimalVar.ToString("0.##"); // returns "0.5"  when decimalVar == 0.5m


or

decimalVar.ToString("0.00"); // returns "0.50"  when decimalVar == 0.5m

Code Snippets

decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m
decimalVar.ToString("0.##"); // returns "0.5"  when decimalVar == 0.5m
decimalVar.ToString("0.00"); // returns "0.50"  when decimalVar == 0.5m

Context

Stack Overflow Q#164926, score: 1231

Revisions (0)

No revisions yet.