Share via


Setting Decimal limited to 2 digits

Question

Tuesday, September 27, 2011 9:06 AM

Hi all,

I've got a problem while limiting a decimal to 2 digit like this 

25 -> 25.00

25.1 -> 25.10

25.15-> 25.15

25.151 - > 25.16

I have tried to find to solution on the web but seems that none of them are solution because I still want the output is in decimal format.

 

Thanks,

Brian

 

 

All replies (3)

Tuesday, September 27, 2011 9:16 AM ✅Answered

Brian,

Explain the context of your question. Is it the display of the value you wish to limit, but keep the original value, or are you trying to manage the input of the value in a field to be consistent, or is it the return value of an input you wish to constrain? 

Ask the right question and the right answer will present itself.

The obvious solution is simply round to 2 decimal places and then format the result. 

this.labelWeightTotal.Text = dWeight.ToString("F2");

dWeight = Math.Round(dWeight, 2);

Hope this helps. 

Regards

Rupert

the problem is not what you don't know it's what you think you know that's wrong


Tuesday, September 27, 2011 9:17 AM ✅Answered

To get Decimal back use Math.Round with Second parameter specifying number of decimal points.

decimal d = 54.9700M;

decimal f = (Math.Round(d, 2)); // 54.97

Console.WriteLine(f.ToString());

To Get String representation of number use String.Format() Specifiying Fixed Points as F2

decimal d = 54.9700M;

string s = String.Format("{0:F2}", d)); // "54.97"


Tuesday, September 27, 2011 9:28 AM ✅Answered

"By limiting to two digits" including when it is a whole number (25 -> 25.00) you are implying a display consideration, not a calculation one. In that case, the way to return a double, single, or decimal with 2 digits is to add the format string "N2" or "F2" as an argument to the ToString method. (See Standard Numeric Format Strings). In both cases the "2" indicates two decimal places. N yields a culture-based formatted number including group separators, while F does not.

The following program illustrates this:

    class Program {
        static void Main(string[] args) {
            decimal decVar = (decimal)1232.120931;
            float singleVar = (Single)1232.120931;
            double dblVar = 1232.120931;

            Console.WriteLine("{0,-10} {1,-8}  {2}", "Type", "N2", "F2");
            Console.WriteLine("{0,-10} {1,-8}  {2}", "Decimal", decVar.ToString("N2"), decVar.ToString("F2"));
            Console.WriteLine("{0,-10} {1,-8}  {2}", "Single", singleVar.ToString("N2"), singleVar.ToString("F2"));
            Console.WriteLine("{0,-10} {1,-8}  {2}", "Double", dblVar.ToString("N2"), dblVar.ToString("F2"));
            Console.ReadKey();
        }
    }

 

Output:

Type       N2        F2
Decimal    1,232.12  1232.12
Single     1,232.12  1232.12
Double     1,232.12  1232.12

 

jmh