![](/img/trans.png)
[英]How to format decimal in c# asp-format tag to 2 decimal points and without trailing zeros if it is an int?
[英]c# How to separate an int with decimal points?
我試圖格式化一個以小數點為分隔符的整數,而不是逗號。
示例: 1234567890應該格式化為1.234.567.890
text_team1.text = em.team1Score.ToString("#,##0");
這將給1,234,567,890
但是,在本主題中,有一些有關使用包含格式樣式的CultureInfo類的信息,因此我使用了其中的幾個:
text_team1.text = em.team1Score.ToString("#,##0", new System.Globalization.CultureInfo("IS-is"));
舉個例子。 但是似乎每個CultureInfo都使用逗號作為分隔符。
即使以后再編輯字符串,仍然會有逗號作為分隔符。
text_team1.text = em.team1Score.ToString("#,##0");
text_team1.text.Replace(',','.');
即使以后再編輯字符串,仍然會有逗號作為分隔符。
text_team1.text = em.team1Score.ToString("#,##0"); text_team1.text.Replace(',','.');
您忘記了分配替換后的字符串。
text_team1.text = text_team1.text.Replace(',','.');
編輯 :
如果仍然不使用“ Replace
功能而希望使用解決方案,則可以使用下面的“擴展”方法。 它適用於strings
和ints
。 如果您不知道擴展方法的工作原理,請Google並閱讀有關擴展方法的信息。
創建ExtensionMethod
腳本並將其放置在項目中的任何文件夾中 :
using System.Globalization;
using System;
public static class ExtensionMethod
{
public static string formatStringWithDot(this string stringToFormat)
{
string convertResult = "";
int tempInt;
if (Int32.TryParse(stringToFormat, out tempInt))
{
convertResult = tempInt.ToString("N0", new NumberFormatInfo()
{
NumberGroupSizes = new[] { 3 },
NumberGroupSeparator = "."
});
}
return convertResult;
}
public static string formatStringWithDot(this int intToFormat)
{
string convertResult = "";
convertResult = intToFormat.ToString("N0", new NumberFormatInfo()
{
NumberGroupSizes = new[] { 3 },
NumberGroupSeparator = "."
});
return convertResult;
}
}
用法 :
string stringToFormat = "1234567890";
Debug.Log(stringToFormat.formatStringWithDot());
要么
int intToFormat = 1234567890;
Debug.Log(intToFormat.formatStringWithDot());
要么
string stringToFormat = "1234567890";
text_team1.text = stringToFormat.formatStringWithDot();
根據遇到的情況使用每個選項。
如果您使用全球化作為格式化字符串的方法,則可以設置自定義組分隔符
NumberFormatInfo nfi = new CultureInfo( "en-US", false ).NumberFormat;
// Displays the same value with a blank as the separator.
Int64 myInt = 1234567890;
nfi.NumberGroupSeparator = ".";
Console.WriteLine( myInt.ToString( "N0", nfi ) );
我更喜歡使用string.Format()
。 您的操作系統是否以這種格式表示數字? 如果是這樣,您可以嘗試使用最簡單的形式
text_team1.text = string.Format("{0:N}", em.team1Score);
或者你可以用
text_team1.text = string.Format(CultureInfo.GetCultureInfo("IS-is"), "{0:N}", em.team1Score);
在乎文化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.