Adam Beck
Adam Beck

Reputation: 1271

How to format a Double when format is variable?

I have a method that takes in 2 numbers. The first number is the value that I want to set (or format) and the second number is the precision to use.

public double ReduceNumber(double Test, int Precision)
{
}

Let's say I pass in the parameters 125.6023867 and 4. I would like the return value to be 125.6023. I know how to use the FormatNumber() function in VB but now that I am trying to convert to C# I am drawing a blank. All that I can find online is String.Format() which helps but I don't know how to code for a format that can change regularly.

Upvotes: 0

Views: 190

Answers (2)

Oded
Oded

Reputation: 498904

A formatted string:

public string ReduceNumber(double Test, int Precision)
{
    return Test.ToString(string.Format("F{0}", Precision));
}

This is using the standard numeric format string "F" with a precision specifier.

A rounded double:

public double ReduceNumber(double Test, int Precision)
{
    return Math.Round(Test, Percision);
}

A point about style - parameter names are normally pascalCase in C#.

Upvotes: 4

MethodMan
MethodMan

Reputation: 18843

here is something you can try it's' a simple method I wrote that adds "," to numbers like 10000 which would return 10,000 also look up using string.Format{"0:d"} for example this is just an idea I am also aware I didn't add percision but that could be passed in to the method as well...

   public static string FormatNumberWithCommas(string inputString)
   {
       string tempString;
       tempString = string.Format("{0:###.####}", Convert.ToInt32(inputString));
       return tempString;
   }

Upvotes: 0

Related Questions