javascript c#中的toFixed函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6938667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 22:24:09  来源:igfitidea点击:

toFixed function in c#

c#javascript

提问by Minh Nguyen

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

在 Javascript 中, toFixed() 方法格式化数字以使用指定数量的尾随小数。 这是 javascript 中的 toFixed 方法

How can i write a same method in c#?

如何在 C# 中编写相同的方法?

回答by Tim

Use the various String.Format() patterns.

使用各种 String.Format() 模式。

For example:

例如:

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

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

将产生 20.00。(2 位小数,因为指定了 N2)。

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

标准数字格式字符串提供了大量关于数字的各种格式字符串的信息,以及一些示例。

回答by R?zvan Flavius Panda

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"

将导致:a:“465.97”,b:“465.9740”,c:“465.9740000000”