如何根据我的十进制位置值显示十进制位置?

本文关键字:位置 十进制 显示 何根 我的 | 更新日期: 2023-09-27 18:04:07

decimal value = 10;
int decimalPosition= 3; //this decimalPosition will be dynamically change.
decimal formatted = Math.Round(value, decimalPosition);

if decimalPosition =3;我需要显示格式化的值,如:10.000。

if decimalPosition =5;我需要显示格式化的值,如:10.00000。

注意:我必须使用Round函数

如何根据我的十进制位置值显示十进制位置?

decimal value没有指定格式-它只是一个数值。您可以指定打印出来的格式,但必须在打印时或创建字符串时指定:

decimal value = 10;
int decimalPosition = 3; //this decimalPosition will be dynamically change.
decimal formatted = Math.Round(value, decimalPosition);
string format = string.Format("{{0:0.{0}}}", string.Concat(Enumerable.Repeat("0", decimalPosition).ToArray()));
string formattedString = string.Format(format, formatted);
Console.WriteLine(formattedString);

打印10.000到控制台

另一种指定格式的方式,如:

var format = string.Format("{{0:f{0}}}", decimalPosition);

您可以尝试这样做:-

decimal.Round(yourValue, decimalPosition, MidpointRounding.AwayFromZero);

你可以试试:——

decimal value = 10;
        int decimalPosition = 3; //this decimalPosition will be dynamically change.
        string position = "";
        for (int i = 0; i < decimalPosition; i++)
        {
            position += "0";
        }
        string newValue = value.ToString() + "." + position;
        decimal formatted = Convert.ToDecimal(newValue);

使用FORMATASNUMBER(Value, decimalPosition)代替math.round

对不起,我忘了是c#而不是VB你可以在MSDN

上读到

http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.strings.formatnumber (v = VS.80) . aspx

命令为String。FormatNumber(blah blah blah)

和ACTUAL声明是…

public static string FormatNumber (
  Object Expression,
  [OptionalAttribute] int NumDigitsAfterDecimal,
  [OptionalAttribute] TriState IncludeLeadingDigit,
  [OptionalAttribute] TriState UseParensForNegativeNumbers,
  [OptionalAttribute] TriState GroupDigits
)