29

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#?

3 Answers 3

44

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.

4
  • 3
    Alternatively, use decimalVar.ToString ("#.##"); as recommended here.
    – meepzh
    Commented Jul 13, 2016 at 19:40
  • @meepzh - That's a valid alternative, but it's worth noting some of the caveats in the comments.
    – Tim
    Commented Jul 13, 2016 at 19:52
  • @Tim, how to do if I need to multiply after converting into #.##?
    – niz_sh
    Commented Sep 3, 2019 at 3:22
  • 1
    @ShuhratjanNizamov - You multiply the values and then convert into the format you want. You can't really do math on strings :)
    – Tim
    Commented Sep 6, 2019 at 0:45
6

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"

0
using System;

namespace ClassLibrary1
{
    public class Program
    {
        public static string ToFixed(decimal value, uint decimals)
        {
            var step = Convert.ToDecimal(Math.Pow(10, decimals));
            return (Math.Truncate((value) * step) / step).ToString();
        }
        static void Main(string[] args)
        {
            Console.WriteLine(ToFixed(3.154567M, 2));
            Console.WriteLine(ToFixed(3.154567M, 3));
            Console.WriteLine(ToFixed(3.154567M, 4));
            Console.WriteLine(ToFixed(3.154567M, 5));
            Console.ReadLine();
        }
    }
}

will result in: 3,15 | 3,154 | 3,1545 | 3,15456 |

Not the answer you're looking for? Browse other questions tagged or ask your own question.