Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`Double.ToString` with N number of decimal places [duplicate]

Tags:

c#

I know that if we want to display a double as a two decimal digit, one would just have to use

public void DisplayTwoDecimal(double dbValue) {   Console.WriteLine(dbValue.ToString("0.00")); } 

But how to extend this to N decimal places, where N is determined by the user?

 public void DisplayNDecimal(double dbValue, int nDecimal)     {      // how to display     } 
like image 812
Graviton Avatar asked Jun 17 '10 07:06

Graviton


People also ask

How do I format a string to two decimal places?

String strDouble = String. 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 %.

How do you print double up to 2 decimal places?

Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.

How do you round a double in a string?

String rounded = String. format("%. 0f", doubleValue); The format method uses HALF_UP rounding which will round up if the value after the fractional part is .


1 Answers

Use "Nx" for x decimal digits.

 public void DisplayNDecimal(double dbValue, int nDecimal)  {    Console.WriteLine(dbValue.ToString("N" + nDecimal));  } 
like image 97
Stefan Avatar answered Oct 09 '22 06:10

Stefan