C# 格式化十进制xamarin

C# 格式化十进制xamarin,c#,xamarin.forms,decimalformat,C#,Xamarin.forms,Decimalformat,我是c#新手,找不到格式化数字的方法。我只想在小数点后显示两位数字 namespace Dolar { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } private void Button_Clicked(object sender, EventArgs e

我是c#新手,找不到格式化数字的方法。我只想在小数点后显示两位数字

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

您可以按如下方式格式化它们:

String.Format("{0:0.00}", 4.5173);    output will be  // "4.51"
或: 通过使用数学课:

float value = 4.5173;
value = System.Math.Round(value,2);

请注意,您没有将解析的
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

我会使用内置格式

在您的例子中,它是
i.ToString(“F2”)
甚至是
i.ToString(“F2”,CultureInfo.InvariantCulture)

2
表示小数点后两位,
F
表示定点格式

见资料来源:

但是,您应该测试一下,因为我不确定这对Xamarin是否正确。这是为.Net准备的