How to override ToString of double?

mc 4,416 Reputation points
2021-01-31T01:28:10.127+00:00

I want to override the function of a double how to do it?

for example:

double total=0.5;

string t=total.ToString();

I want it return a format that is specified.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,842 questions
0 comments No comments
{count} votes

Accepted answer
  1. Alberto Poblacion 1,556 Reputation points
    2021-01-31T09:58:00.867+00:00

    If, after experimenting with the formats for ToString, you do not find any that satisfies your needs, then you can go back to the original question of "how to override ToString". Now, you cannot actually override it because overriding would require inheriting from double, which is not allowed. But you can instead create an extension method. You do that by adding a static method in a static class that takes "this double" as a parameter:

        public static class MyExtenders
        {
            public static string ToStringWithMyFormat(this double d)
            {
                string s = d.ToString(); // Make changes here to format d in whichever way you want it
                return s;
            }
        }
    
        // Use it like this:
        string t=total.ToStringWithMyFormat();
    

2 additional answers

Sort by: Most helpful
  1. Bonnie DeWitt 811 Reputation points
    2021-01-31T01:51:24.523+00:00

    I'm not sure why you have a problem (or I'm don't understand why you're asking), you just put the format as a parameter in the .ToString().

    double dbl = 0.5;
    string dblString = dbl.ToString("0.00");
    // some more examples:
    dblString = dbl.ToString("F");
    dblString = dbl.ToString("0.#");
    dblString = dbl.ToString("0.##");
    dblString = dbl.ToString("N");
    dblString = dbl.ToString("N2");
    dblString = dbl.ToString("N4");
    

    Is that what you're asking about?


    ~~Bonnie DeWitt [MVP since 2003]
    [http://geek-goddess-bonnie.blogspot.com]1


  2. Sharad Jaiswal 1 Reputation point
    2021-01-31T11:07:36.65+00:00

    According to tutorialspoints
    The java.lang.Double.toString() method returns a string representation of this Double object.
    Below is complete demonstrations

    package com.tutorialspoint;

    import java.lang.*;

    public class DoubleDemo {

    public static void main(String[] args) {

      Double d = new Double("5.3");
    
      // returns a string representation
      String retval = d.toString();
      System.out.println("Value = " + retval);
    

    }
    }

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.