Click here to Skip to main content
15,902,812 members
Please Sign up or sign in to vote.
3.67/5 (3 votes)
See more:
C#
string[] final = new string[result.Length];             

                for (int splitCount = 0; splitCount < result.Length; splitCount++)
                {
                    MatchCollection match = Regex.Matches(result[splitCount], @"\d+(\.\d+)?");

                    foreach (Match m in match)
                    {
                        final[splitCount] += (Double.Parse(m.Value, new System.Globalization.NumberFormatInfo() { NumberDecimalSeparator = "." })).ToString()+"            ";
                    }
                }




How to round off the double value to 4 digits in the above code
Posted

C#
string[] final = new string[result.Length];             
for (int splitCount = 0; splitCount < result.Length; splitCount++)
{
  MatchCollection match = Regex.Matches(result[splitCount], @"\d+(?:\.\d*)?");
  final[splitCount] = string.Empty;      // Don't forget to initialize the entries in final.
  foreach (Match m in match)
  {
    final[splitCount] += Double.Parse(m.Value, System.Globalization.CultureInfo.InvariantCulture).ToString("F4")+"            ";
  }
}

Just use the format info in the .ToString() to control the precision.
I changed the regex so that it was a noncapturing group and to allow for decimal point without following digits. E.g., "1234."
 
Share this answer
 
Use the Math.Round[^] function.
 
Share this answer
 
Comments
KUMAR619 31-Mar-14 2:18am    
Thanks but by task is to round number to 4 digits as shown below

13.3456788-->13.3456

23.23-->23.2300

Add 0 if has lesser digits or trim them if has more digits
int round(double number)
{
return (number >= 0) ? (int)(number + 0.5) : (int)(number - 0.5);
}



Use Long Instead Of Int If You have A long No

And Another Way Is

double a = 2.333333;
System.Math.Round(a)
Use Math Funtion
 
Share this answer
 
v2
Comments
KUMAR619 31-Mar-14 2:19am    
Thanks but by task is to round number to 4 digits as shown below

13.3456788-->13.3456

23.23-->23.2300

Add 0 if has lesser digits or trim them if has more digits
Rao Lokesh 31-Mar-14 2:20am    
double a = 2.333333;
System.Math.Round(a)

After This U Can Convert It Into Format You Want
Rao Lokesh 31-Mar-14 2:25am    
Mark As Answer If You Get Answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900