2013-01-15 53 views
1

前一個點是有可能得到使用的String.Format從int a = 456;像「45.6」的字符串?插入最後一個字符

+0

檢查此鏈接:http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx – Boomer

回答

3

數學運算可能會產生在不同的文化不同的結果。您可能會得到,而不是.。試試這個

var aStr = a.ToString(); 
var res = aStr.Insert(aStr.Length - 1, ".") 
+0

是的,也許這是最好的解決方案,但thx所有,所有答案都很有用。 – Taras

2

除以10(雙倍)。

你需要採取當前區域性進去了。要始終獲得點,請使用InvariantCulture

爲了避免浮點不精確的問題(類似45 - > 4.49999999),請務必只通過指定「0.0」格式打印的第一位。

int i = 123; 
var s = String.Format (CultureInfo.InvariantCulture, "{0:0.0}", i/10.0); 
+0

爲了保持精度,您還可以除以十進制數,而不是浮點數/雙精度數。即打印'I/10m' –

+0

@HonzaBrestan這是一個非常討厭/巧招:) – mafu

0

您可以使用IFormatProvider來實現。 (可以自定義成任意格式)

int val = 456; 
string s = string.Format(new CustomerFormatter(),"{0:1d}", val); 
string s1 = string.Format(new CustomerFormatter(), "{0:2d}", val); 
Console.WriteLine(s); //45.6 
Console.WriteLine(s1); //4.56 

public class CustomerFormatter : IFormatProvider, ICustomFormatter 
{ 
    public object GetFormat(Type formatType) 
    { 
     if (formatType == typeof(ICustomFormatter)) 
      return this; 
     else 
      return null; 
    } 

    public string Format(string format, object arg, IFormatProvider formatProvider) 
    { 
     if (!this.Equals(formatProvider)) 
     { 
      return null; 
     } 
     else 
     { 
      string customerString = arg.ToString(); 
      switch (format) 
      { 
       case "1d": 
        return customerString.Insert(customerString.Length - 1, "."); 
       case "2d": 
        return customerString.Insert(customerString.Length - 2, "."); 

       default: 
        return customerString; 
      } 
     } 
    } 
} 
0
 int a = 456; 
     String aString = String.Format("{0}{1}{2}", a/10, ".", a % 10); 
0
Int32 a = 456; 

String aString = a.ToString(); 
aString = aString.Insert((aString.Length - 1), ".")