24

in Javascript, the toFixed() method formats a number to use a specified number of trailing decimals. Here is toFixed method in javascript

How can i write a same method in c#?

Minh Nguyen
  • 1,909
  • 3
  • 16
  • 30

2 Answers2

34

Use the various String.Format() patterns.

For example:

int someNumber = 20;
string strNumber = someNumber.ToString("N2");

Would produce 20.00. (2 decimal places because N2 was specified).

Standard Numeric Format Strings gives a lot of information on the various format strings for numbers, along with some examples.

Tim
  • 27,799
  • 8
  • 61
  • 74
  • 2
    Alternatively, use `decimalVar.ToString ("#.##");` as recommended [here](http://stackoverflow.com/questions/164926/c-sharp-how-do-i-round-a-decimal-value-to-2-decimal-places-for-output-on-a-pa). – meepzh Jul 13 '16 at 19:40
  • @meepzh - That's a valid alternative, but it's worth noting some of the caveats in the comments. – Tim Jul 13 '16 at 19:52
  • @Tim, how to do if I need to multiply after converting into #.##? – niz_sh Sep 03 '19 at 03:22
  • 1
    @ShuhratjanNizamov - You multiply the values and *then* convert into the format you want. You can't really do math on strings :) – Tim Sep 06 '19 at 00:45
5

You could make an extension method like this:

using System;

namespace toFixedExample
{
    public static class MyExtensionMethods
    {
        public static string toFixed(this double number, uint decimals)
        {
            return number.ToString("N" + decimals);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            double d = 465.974;
            var a = d.toFixed(2);
            var b = d.toFixed(4);
            var c = d.toFixed(10);
        }
    }
}

will result in: a: "465.97", b: "465.9740", c: "465.9740000000"

Răzvan Flavius Panda
  • 21,136
  • 15
  • 108
  • 159