开发者

toFixed function in c#

开发者 https://www.devze.com 2023-03-26 07:18 出处:网络
in Javascript, the toFixed() method formats a num开发者_JS百科ber to use a specified number of trailing decimals.

in Javascript, the toFixed() method formats a num开发者_JS百科ber to use a specified number of trailing decimals. Here is toFixed method in javascript

How can i write a same method in c#?


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.


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"


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 |

0

精彩评论

暂无评论...
验证码 换一张
取 消