首页 > 解决方案 > 格式化十进制 xamarin

问题描述

我是 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

标签: c#xamarin.formsdecimalformat

解决方案


你可以像这样格式化它们:

String.Format("{0:0.00}", 4.5173);    output will be  // "4.51"

或:通过使用数学类:

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

推荐阅读