前一個點是有可能得到使用的String.Format從int a = 456;
像「45.6」的字符串?插入最後一個字符
插入最後一個字符
回答
數學運算可能會產生在不同的文化不同的結果。您可能會得到,
而不是.
。試試這個
var aStr = a.ToString();
var res = aStr.Insert(aStr.Length - 1, ".")
是的,也許這是最好的解決方案,但thx所有,所有答案都很有用。 – Taras
除以10(雙倍)。
你需要採取當前區域性進去了。要始終獲得點,請使用InvariantCulture
。
爲了避免浮點不精確的問題(類似45 - > 4.49999999),請務必只通過指定「0.0」格式打印的第一位。
int i = 123;
var s = String.Format (CultureInfo.InvariantCulture, "{0:0.0}", i/10.0);
爲了保持精度,您還可以除以十進制數,而不是浮點數/雙精度數。即打印'I/10m' –
@HonzaBrestan這是一個非常討厭/巧招:) – mafu
您可以使用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;
}
}
}
}
int a = 456;
String aString = String.Format("{0}{1}{2}", a/10, ".", a % 10);
Int32 a = 456;
String aString = a.ToString();
aString = aString.Insert((aString.Length - 1), ".")
- 1. jQuery的文字插入到一個字符串後最後/
- 2. 得到最後一個字符在插入符號前插入位置
- 3. 在字符串的第一個和最後一個位置插入字符
- 4. 插入最後一個ID
- 5. 插入字符之前第6個字符從最後jquery
- 6. 最後一個字符串
- 7. 每個「!」後插入換行符字符
- 8. 刪除字符串中最後一個空格後的最後一個字符
- 9. 插入MySQL的最後一個ID每次插入後
- 10. 字符串的第一個字符和最後一個字符
- 11. 建立一個字符串,然後插入到另一個表
- 12. pdo中的最後一個插入ID
- 13. sqlalchemy和最後一個插入ID
- 14. 獲取最後一個插入的ID
- 15. Propel/mssql:最後一個插入ID
- 16. 抓取最後一個插入ID sqlsrv
- 17. 獲取最後一個插入ID
- 18. 選擇最後一個插入ID
- 19. 如何在最後一行之前插入字符串?
- 20. 使用fseek在最後一行之前插入字符串
- 21. 只插入最後一排
- 22. 從最後插入的行中獲取最後一個插入ID
- 23. 字符串:提取最後六個字符後的最後一個/
- 24. 在最後三個字符之前插入破折號
- 25. 在javascript中插入最後2個字符之前
- 26. 數據庫PHP插入網址最後2個字符
- 27. 插入字符串後4個結果
- 28. 字符串中最後一個數字
- 29. 如何在受控輸入的最後一個字符後設置插入符號?
- 30. 如何替換最後一個字符並將字符插入字符串的開頭?
檢查此鏈接:http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx – Boomer