locked
How to format double value RRS feed

  • Question

  • How we can format right part of the double value based on some value like below.

    0.01678 (values 1,2,3...)

    0.016 (if values is 3 then i need to display 3 numbers from right part of the double value)

    0.01 (if if values is 2 then i need to display 2 numbers from right part of the double value)

    Thanks, @nag

    Wednesday, August 29, 2012 10:04 AM

Answers

  • To display 3 decimal places, use a formatting string:

    result.ToString("0.000")

    Thursday, August 30, 2012 12:44 PM
  • .ToString(#0.000) this works for me, but i need to send value return as double value so again i need to convert from string to double after formating but again it neglecting zero after converts to double.

    0.480 - After formating using .Tostring(0.000)

    0.48 - After converting above string value to to double but i want 0.480

    any one help me out

    It will work
    string x = string.Format("{0:n3}",double.Parse("0.480"));


    Web Developer

    Friday, August 31, 2012 2:00 PM
  • Hi, check out this code I did, and be attention how do I create a string of a custom length of decimal places. The code has a loop of 10 numbers, and on each loop code generate a random decimal number (dec) and a number of decimals (value) for each number.

    Then code creates a formated string to show the random number of decimals for each of 10 numbers.

    public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                StringBuilder sb = new StringBuilder();
                Random r = new Random();
                for (int i = 0; i < 10; i++)
                {
                    int value = r.Next(1, 10);
                    decimal dec = Calc1.NextDecimal(r);
                    string strFormat = "0:0.";
                    for (int j = 0; j < value; j++)
                        strFormat += "0";
                    string decRounded = string.Format("{" + strFormat + "}", dec);
                    sb.AppendLine(string.Format("Actual number: {0}\r\nNumber of decimals: {1}\r\nRounded number: {2}\r\n{3}",
                        dec, value, decRounded, "---"));
                }
                MessageBox.Show(sb.ToString());
            }       
        }
    
        static class Calc1
        {
            public static decimal NextDecimal(this Random r)
            {
                var a = (int)(uint.MaxValue * r.NextDouble());
                var b = (int)(uint.MaxValue * r.NextDouble());
                var c = (int)(uint.MaxValue * r.NextDouble());
                var n = r.NextDouble() > 0.5;
                var s = (byte)(29 * r.NextDouble());
                return new Decimal(a, b, c, n, s);
            }
        }
    
        static class Calc
        {
            public static decimal NextDecimal(this Random rng)
            {
                byte scale = (byte)rng.Next(29);
                bool sign = rng.Next(2) == 1;
                return new decimal(rng.NextInt32(),
                                   rng.NextInt32(),
                                   rng.NextInt32(),
                                   sign,
                                   scale);
            }
    
            private static int NextInt32(this Random rng)
            {
                unchecked
                {
                    int firstBits = rng.Next(0, 1 << 4) << 28;
                    int lastBits = rng.Next(0, 1 << 28);
                    return firstBits | lastBits;
                }
            }
        }

    Hope it helps to understand how you can create a custom formats (by appending text, I used += operators).


    Mitja



    Monday, September 3, 2012 11:06 AM
  • Try this:


    private void MainMethod()
    {
    	double d = 001678.001678;
    	Console.WriteLine(Fix(d, 3));
    }
    
    private double Fix(double d, int places)
    {
    	string s = d.ToString();
    	string pattern = @"[0-9]+(\.[0-9]+)";
    	if (Regex.IsMatch(s, pattern))
    	{
    		string decimals = Regex.Match(s, pattern).Groups[1].Value;
    		return double.Parse(s.Replace(decimals, decimals.Substring(0, places + 1)));
    	}
    
    	return 0.0;
    }


    You just want to trim down to a certain number of decimals without rounding? The example above returns a double value of 0.001 where the 1 is not rounded because of the number following it regardless of what it is.

    ~Ace


    If a post helps you in any way or solves your particular issue, please remember to use the Propose As Answer option or Vote As Helpful
    Visit the Forum: TechLifeForum





    Tuesday, September 4, 2012 4:57 AM

All replies

  • Hi Murali,

    Use Math.Round(value, digits)

    ex :

    using System;

    public class Example
    {
       public static void Main()
       {
          double[] values = { 2.125, 2.135, 2.145, 3.125, 3.135, 3.145 };
          foreach (double value in values)
             Console.WriteLine("{0} --> {1}", value, Math.Round(value, 2));

       }
    }

    // The example displays the following output: 
    //       2.125 --> 2.12 
    //       2.135 --> 2.13 
    //       2.145 --> 2.14 
    //       3.125 --> 3.12 
    //       3.135 --> 3.14 
    //       3.145 --> 3.14


    Thanks in Advance Suresh M
    If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful"

    Wednesday, August 29, 2012 10:19 AM
  • double db = 0.01678;
    string str = db.ToString();
    string str1 = str.Split('.')[0].ToString() + "." + str.Split('.')[1].ToString().Substring(0, 1 );
    string str2 = str.Split('.')[0].ToString() + "." + str.Split('.')[1].ToString().Substring(0, 2);
    string str3 = str.Split('.')[0].ToString() + "." + str.Split('.')[1].ToString().Substring(0, 3);

    Math.Round() will round off the values to nearest one, in your case you need the exact one. It will be better to use string function in this case.

    regards

    joon

    Wednesday, August 29, 2012 10:26 AM
  • Try this as well:

    double d = 0.01678;
    int value = 2;
    string s = string.Format( "{0:F" + value + "}", d );

    It also rounds the number.

    Wednesday, August 29, 2012 11:16 AM
  • Math.Round(doubleValue, digitsNumber) allow you to do that. Check this msdn link Standard Numeric Format Strings


    Web Developer

    Wednesday, August 29, 2012 11:33 AM
  • But i want exact value if value is 0.0168 then after round it giving me 0.02 but i want 0.01

    Wednesday, August 29, 2012 11:57 AM
  • @Viorel

    Its not working i tried it after formating i'm getting 0.01678 with value=3 but it should return 0.016 and my actual number may get bigger like 0.016789478567474 like this

    Wednesday, August 29, 2012 12:00 PM
  • @Viorel

    Its not working i tried it after formating i'm getting 0.01678 with value=3 but it should return 0.016 and my actual number may get bigger like 0.016789478567474 like this

    what is the wrong with using string function, are you getting any error??

    double db = 0.01678;
    string str = db.ToString();
    string str1 = str.Split('.')[0].ToString() + "." + str.Split('.')[1].ToString().Substring(0, 1 );
    string str2 = str.Split('.')[0].ToString() + "." + str.Split('.')[1].ToString().Substring(0, 2);
    string str3 = str.Split('.')[0].ToString() + "." + str.Split('.')[1].ToString().Substring(0, 3);

    regards

    joon

    Wednesday, August 29, 2012 12:07 PM
  • @joon

    No but if i get value like 0.00000075 its giving me wrong after .Tostring() like 7E+some value and remaining cases 'm getting with less than one value i think you need to add +1 in substring method right?

    string str1 = str.Split('.')[0].ToString() + "." + str.Split('.')[1].ToString().Substring(0, value+1 );

    also getting error if value is zero

    Wednesday, August 29, 2012 12:19 PM
  • @joon

    Also one more is if value is 1.0 and value to take substring part is 3 then i need to display like 1.000 but in your code its giving me indexoutof error.

    Wednesday, August 29, 2012 12:22 PM
  • @joon

    Also one more is if value is 1.0 and value to take substring part is 3 then i need to display like 1.000 but in your code its giving me indexoutof error.

    i got it. Anyways you may take help of string conversion, again i guess it will round off. So may be you can write your own logic with conditions, say greater than 1 then so, less than 0 so. Maybe yoo can try to use decimal type instead of double type(maybe little bit away from your requirement), double values are always tried to be rounded off.

    double db = 1.0;// 0.00000075;
    string s = string.Format("{0:N" + 3 + "}", db);

    regards

    joon



    • Edited by Joon84 Wednesday, August 29, 2012 12:56 PM
    Wednesday, August 29, 2012 12:53 PM
  • Here two function to round floor or ceiling.

    You should use the round floor

    private static decimal roundFloor(decimal d, int decimalPlaces)
            {
                decimal p = (decimal)(Math.Pow(10, decimalPlaces));
    
                decimal res = d * p;
                res = Math.Floor(res);
                res = res / p;
    
                return res;
            }
    
            private static decimal roundCeiling(decimal d, int decimalPlaces)
            {
                decimal p = (decimal)(Math.Pow(10, decimalPlaces));
                
                decimal res = d * p;
                res = Math.Ceiling(res);
                res = res / p;
    
                return res;
            }


    Regards,
    Bubu
    http://zsvipullo.blogspot.it

    Please mark my answer if it helped you, I would greatly appreciate it.

    Wednesday, August 29, 2012 12:55 PM
  • // if you wish 4 digits then go for 4+1 then remove the last one
    double db = 0.016789478567474;
    string str = db.ToString("#0.00000").Substring(0,db.ToString("#0.00000").Length -1); 
    
    db = 1.0;
    str = db.ToString("#0.00000").Substring(0, db.ToString("#0.00000").Length - 1);
    
    db = 0.00000075;
    str = db.ToString("#0.00000").Substring(0, db.ToString("#0.00000").Length - 1);

    check this link http://stackoverflow.com/questions/928407/how-to-show-number-without-rounding-off-numbers

    regards

    joon


    • Edited by Joon84 Wednesday, August 29, 2012 1:04 PM
    Wednesday, August 29, 2012 1:02 PM
  • Here a more elegant solution

    http://zsvipullo.blogspot.it/2012/08/roundfloor-roundceiling_29.html


    Regards,
    Bubu
    http://zsvipullo.blogspot.it

    Please mark my answer if it helped you, I would greatly appreciate it.

    Wednesday, August 29, 2012 2:06 PM
  • Here two function to round floor or ceiling.

    You should use the round floor

    private static decimal roundFloor(decimal d, int decimalPlaces)
            {
                decimal p = (decimal)(Math.Pow(10, decimalPlaces));
    
                decimal res = d * p;
                res = Math.Floor(res);
                res = res / p;
    
                return res;
            }
    
            private static decimal roundCeiling(decimal d, int decimalPlaces)
            {
                decimal p = (decimal)(Math.Pow(10, decimalPlaces));
                
                decimal res = d * p;
                res = Math.Ceiling(res);
                res = res / p;
    
                return res;
            }


    Regards,
    Bubu
    http://zsvipullo.blogspot.it

    Please mark my answer if it helped you, I would greatly appreciate it.

    I'm getting like this...

    decimal p = (decimal)(Math.Pow(10, decimalPlaces)); // p=1000.0 

                decimal res = d * p; // 480.630000005 where d=0.48063453
                res = Math.Floor(res); // 480.0

                res = res / p; // 0.48

                return res;

    But i want 0.480 it giving me only 0.48

    Thursday, August 30, 2012 7:03 AM
  • @sergio

    If value is 481.0 then it gives me correct value 0.481

    If value is 480.0 then it give 0.48 after floor and divide with respective decimal places (1000)

    so can you please tell me the case when value is ended with zero like 480 and in that case only 'm getting incorrect decimal places like 0.48 out of 0.480

    Thanks,

    @nag

    Thursday, August 30, 2012 7:14 AM
  • To display 3 decimal places, use a formatting string:

    result.ToString("0.000")

    Thursday, August 30, 2012 12:44 PM
  • I would be very careful of searching for a decimal separator using a character literal as shown here, the ToString() method is culture sensitive, and in many cultures the decimal separator is a comma and not a point.
    Thursday, August 30, 2012 7:10 PM
  • I would be very careful of searching for a decimal separator using a character literal as shown here, the ToString() method is culture sensitive, and in many cultures the decimal separator is a comma and not a point.
    I think he can easily solve it by setting InvariantCulture at thread level, or even can set the property culture when he do the format

    Web Developer

    Thursday, August 30, 2012 7:25 PM
  • @Fox

    so tell me is that .ToString(#0.000) 'll work for me or not? or any suggestions on it from your side.

    Thursday, August 30, 2012 7:57 PM
  • @Fox

    so tell me is that .ToString(#0.000) 'll work for me or not? or any suggestions on it from your side.

    Murali, the solution .ToString("#0.0") will work if your culture has the decimal separator as a comma or a dot.

    The solution string str1 = str.Split('.')[0].ToString() + "." + str.Split('.')[1].ToString().Substring(0, 1 );
    assumes the decimal separator of the current culture is a dot. Even if you would (like Norkk said) explicitly set the culture of the thread or the formatter to InvariantCulture to have a more robust solution, a culture-specific dot is being manually inserted (+ "." +).

    Thursday, August 30, 2012 8:20 PM
  • .ToString(#0.000) this works for me, but i need to send value return as double value so again i need to convert from string to double after formating but again it neglecting zero after converts to double.

    0.480 - After formating using .Tostring(0.000)

    0.48 - After converting above string value to to double but i want 0.480

    any one help me out

    Friday, August 31, 2012 1:42 PM
  • .ToString(#0.000) this works for me, but i need to send value return as double value so again i need to convert from string to double after formating but again it neglecting zero after converts to double.

    0.480 - After formating using .Tostring(0.000)

    0.48 - After converting above string value to to double but i want 0.480

    any one help me out

    It will work
    string x = string.Format("{0:n3}",double.Parse("0.480"));


    Web Developer

    Friday, August 31, 2012 2:00 PM
  • How we can format right part of the double value based on some value like below.

    0.01678 (values 1,2,3...)

    0.016 (if values is 3 then i need to display 3 numbers from right part of the double value)

    0.01 (if if values is 2 then i need to display 2 numbers from right part of the double value)

    Thanks, @nag

    Iam still not sure what exactly are you trying to do!

    What do you mean by "(valeus 1,2,2,...)" and "(if values is 4 then...)"?


    Mitja

    Saturday, September 1, 2012 1:32 PM
  • @Mitita

    Those values are decimal places that i need to display the output. If value is 4 then from the value 0.01678 i need to display 0.0167 (four decimal places from the value) Got it!

    Thanks,

    @nag

    Monday, September 3, 2012 10:12 AM
  • But where do you get this so called value?

    Mitja

    Monday, September 3, 2012 10:38 AM
  • Hi, check out this code I did, and be attention how do I create a string of a custom length of decimal places. The code has a loop of 10 numbers, and on each loop code generate a random decimal number (dec) and a number of decimals (value) for each number.

    Then code creates a formated string to show the random number of decimals for each of 10 numbers.

    public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                StringBuilder sb = new StringBuilder();
                Random r = new Random();
                for (int i = 0; i < 10; i++)
                {
                    int value = r.Next(1, 10);
                    decimal dec = Calc1.NextDecimal(r);
                    string strFormat = "0:0.";
                    for (int j = 0; j < value; j++)
                        strFormat += "0";
                    string decRounded = string.Format("{" + strFormat + "}", dec);
                    sb.AppendLine(string.Format("Actual number: {0}\r\nNumber of decimals: {1}\r\nRounded number: {2}\r\n{3}",
                        dec, value, decRounded, "---"));
                }
                MessageBox.Show(sb.ToString());
            }       
        }
    
        static class Calc1
        {
            public static decimal NextDecimal(this Random r)
            {
                var a = (int)(uint.MaxValue * r.NextDouble());
                var b = (int)(uint.MaxValue * r.NextDouble());
                var c = (int)(uint.MaxValue * r.NextDouble());
                var n = r.NextDouble() > 0.5;
                var s = (byte)(29 * r.NextDouble());
                return new Decimal(a, b, c, n, s);
            }
        }
    
        static class Calc
        {
            public static decimal NextDecimal(this Random rng)
            {
                byte scale = (byte)rng.Next(29);
                bool sign = rng.Next(2) == 1;
                return new decimal(rng.NextInt32(),
                                   rng.NextInt32(),
                                   rng.NextInt32(),
                                   sign,
                                   scale);
            }
    
            private static int NextInt32(this Random rng)
            {
                unchecked
                {
                    int firstBits = rng.Next(0, 1 << 4) << 28;
                    int lastBits = rng.Next(0, 1 << 28);
                    return firstBits | lastBits;
                }
            }
        }

    Hope it helps to understand how you can create a custom formats (by appending text, I used += operators).


    Mitja



    Monday, September 3, 2012 11:06 AM
  • Try this:


    private void MainMethod()
    {
    	double d = 001678.001678;
    	Console.WriteLine(Fix(d, 3));
    }
    
    private double Fix(double d, int places)
    {
    	string s = d.ToString();
    	string pattern = @"[0-9]+(\.[0-9]+)";
    	if (Regex.IsMatch(s, pattern))
    	{
    		string decimals = Regex.Match(s, pattern).Groups[1].Value;
    		return double.Parse(s.Replace(decimals, decimals.Substring(0, places + 1)));
    	}
    
    	return 0.0;
    }


    You just want to trim down to a certain number of decimals without rounding? The example above returns a double value of 0.001 where the 1 is not rounded because of the number following it regardless of what it is.

    ~Ace


    If a post helps you in any way or solves your particular issue, please remember to use the Propose As Answer option or Vote As Helpful
    Visit the Forum: TechLifeForum





    Tuesday, September 4, 2012 4:57 AM