Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format a decimal using at least 2 places and at most 6 places

Tags:

c#

.net

decimal

To meet a specification I need to format a decimal value with the rule:

  • All values must have at least two decimal places and at most six.

Example:

Value        Formatted
1            1.00
1.1          1.10
1.1234       1.1234
1.123456     1.123456
1.12345678   1.123456

I guess I'll end using a condition, but I wonder if there is a format string which can do this.

like image 544
MiguelM Avatar asked Jul 18 '11 20:07

MiguelM


People also ask

How many decimal places are there in a number?

And from a number of 4 decimal places it provided a number to 2 decimal places. If you notice, you will see in the Average column the number was 748.6667, but in the Rounded Average column the value is 748.67. Hope you can remember, whenever the leaving digit is going to be more or equal 5, 1 is added to the right most remaining digit.

Can I have more than two decimal places in my format?

Of course, you’re not just limited to two decimal places – you can specify more decimal places in your format model if required. Here’s an example that uses the ROUND (number) function:

How to format a number using the decimalformat?

You can format a number using the DecimalFormat#format (number) method. The DecimalFormat takes a String pattern indicating how to format the decimal. In first case we format a decimal using 4 grouping numbers and use the comma as a grouping separator. Show only 2 decimals after the comma and use the point as a decimal separator.

How do I round a number to two decimal places?

When using Oracle Database, you can use functions like TO_CHAR (number) to return numbers as a string, formatted to two decimal places (or however many decimal places you require). Or you can use functions like ROUND (number) and TRUNC (number) to round or truncate the number to your required number of decimal places.


1 Answers

Have you tried:

.ToString("0.00####");

like image 143
Barry Kaye Avatar answered Oct 18 '22 21:10

Barry Kaye