我是c#的新手,我无法找到格式化数字的方法。我想在小数点后只显示2位数。
namespace Dolar
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}
private void Button_Clicked(object sender, EventArgs e)
{
XmlDocument doc1 = new XmlDocument();
doc1.Load("http://www.tcmb.gov.tr/kurlar/today.xml");
XmlElement root = doc1.DocumentElement;
XmlNodeList nodes = root.SelectNodes("Currency");
foreach (XmlNode node in nodes)
{
var attributeKod = node.Attributes["Kod"].Value;
if (attributeKod.Equals("USD"))
{
var a = node.SelectNodes("BanknoteSelling")[0].InnerText;
var b = node.SelectNodes("BanknoteBuying")[0].InnerText;
float c = float.Parse(a);
float d = float.Parse(b);
label2.Text = a;
label3.Text = b;
}
var attributeKod1 = node.Attributes["Kod"].Value;
if(attributeKod1.Equals("EUR"))
{
var a = node.SelectNodes("BanknoteSelling")[0].InnerText;
var b = node.SelectNodes("BanknoteBuying")[0].InnerText;
float c = float.Parse(a);
float d = float.Parse(b);
label4.Text = a;
label5.Text = b;
}
}
}
}
}
输出是;
4.5173 //4.51
4.4992 //4.49
5.3131 //5.31
5.2919 //5.29
答案 0 :(得分:1)
你可以像这样格式化它们:
String.Format("{0:0.00}", 4.5173); output will be // "4.51"
或: 使用Math类:
float value = 4.5173;
value = System.Math.Round(value,2);
答案 1 :(得分:0)
请注意,您没有将已解析的float
变量(c和d)分配给文本框。您可以使用格式说明符“0.00”,如下所示:
var c = float.Parse(a);
var d = float.Parse(b);
label4.Text = c.ToString("0.00");
label5.Text = d.ToString("0.00");
您还混合了隐式类型var
变量和显式类型变量(例如float c
)。我建议坚持var
答案 2 :(得分:0)
我会使用内置格式。
在您的情况下,{x:Static CDataJoueurs.Instance}
甚至是i.ToString("F2")
。
i.ToString("F2", CultureInfo.InvariantCulture)
表示2位小数,2
表示定点格式。
然而,你应该对此进行测试,因为我不确定这对Xamarin是否正确。这是.Net。