Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 984
wows Avatar asked Oct 02 '08 22:10

wows


People also ask

How do you display upto 2 decimal places?

1. DecimalFormat(“0.00”) We can use DecimalFormat("0.00") to ensure the number is round to 2 decimal places.

How do you format a number to two decimal places in Python?

In Python, to print 2 decimal places we will use str. format() with “{:. 2f}” as string and float as a number. Call print and it will print the float with 2 decimal places.

How do you print float to two decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.


1 Answers

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 
like image 64
albertein Avatar answered Sep 22 '22 03:09

albertein