2013-03-16 64 views
1
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函數。

+0

爲什麼必須用'Round'? – MarcinJuraszek 2013-03-16 12:32:29

回答

0

使用FORMATASNUMBER(價值,decimalPosition),而不是math.round的

對不起,我忘了這是C#不VB 但是你可以在MSDN這裏讀到它

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

命令是String.FormatNumber(等於等於等於)

和ACTUAL聲明是...

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

C#中沒有這種東西# – MarcinJuraszek 2013-03-16 12:33:49

+0

單擊上面示例中的鏈接,查看c#示例。證據是存在的,它的c# – Zeddy 2013-03-16 14:18:30

+0

是的,有'Strings.FormatNumber'方法,但沒有一個叫'FORMATASNUMBER',我聲稱。 – MarcinJuraszek 2013-03-16 14:19:42

1

你可以嘗試這樣的事情: -

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

decimal值沒有指定格式 - 它只是一個數值。你可以指定它是被打印出來的格式,但你必須這樣做,在打印或正在創建的字符串時:

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); 
+0

這裏硬編碼「0」值(Enumerable.Repeat(「0」,decimalPosition)) – Kavitha 2013-03-16 12:45:16

+0

不,這只是一個模式。 – MarcinJuraszek 2013-03-16 12:45:33

+0

不用硬編碼可以嗎? – Kavitha 2013-03-16 12:45:48

0

ü可以嘗試: -

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); 
+0

@Neeru Bindela你不需要使用任何額外的功能 – 2013-03-16 12:56:29

+0

感謝您的幫助。但格式化的值是10.Not 10.000 – Kavitha 2013-03-16 13:28:42

+0

@Neeru Bindela Response.Write(formatted.ToString());它是給你想要的結果相同 – 2013-03-16 13:35:18

相關問題