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 }
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 %.
Just use %. 2f as the format specifier. This will make the Java printf format a double to two decimal places.
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 .
Use "Nx" for x decimal digits.
public void DisplayNDecimal(double dbValue, int nDecimal) { Console.WriteLine(dbValue.ToString("N" + nDecimal)); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With