[英]How do you round a decimal number in C sharp?
我正在嘗試編寫一些將英鎊轉換為美元的代碼。 轉換器工具工作正常。 但是,我正在努力舍入小數。 例如,當我兌換 24.50 英鎊時,我的工具輸出 31.8500 美元,而我希望它輸出 31.75 美元。 我已經嘗試過 Math.Round(); 方法,但不幸的是我並沒有未能得到我想要的結果。
這是我的代碼,我做錯了什么?
using System;
using System.Windows.Forms;
namespace currencyconverter
{
public partial class currencyconv : Form
{
decimal US_Dollars = Math.Round(1.30m,2);
decimal Australian_Dollars = 1.87m;
decimal European_Euros = 1.17m;
public currencyconv()
{
InitializeComponent();
}
private void currencyconv_Load(object sender, EventArgs e)
{
cmbcurrency.Text = "Select a currency";
}
private void btnExit_Click(object sender, EventArgs e)
{
Close();
}
private void btnConvert_Click(object sender, EventArgs e)
{
if (cmbcurrency.SelectedIndex == -1 || (string.IsNullOrWhiteSpace(txtconvert.Text)))
{
System.Windows.Forms.MessageBox.Show("Please complete the required fields.");
}
else
{
decimal British_Pound = decimal.Parse(txtconvert.Text);
if (cmbcurrency.Text == "USD")
{
txtresult.Text = System.Convert.ToString(("$" + British_Pound * US_Dollars));
}
if (cmbcurrency.Text == "AUD")
{
txtresult.Text = System.Convert.ToString(("$" + British_Pound * Australian_Dollars));
}
if (cmbcurrency.Text == "EUR")
{
txtresult.Text = System.Convert.ToString(("€" + British_Pound * European_Euros));
}
}
}
private void txtconvert_KeyPress(object sender, KeyPressEventArgs e)
{
Char chr = e.KeyChar;
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.')
{
e.Handled = true;
MessageBox.Show("Please enter a numerical value.");
}
if(e.KeyChar == '.' && (txtconvert.Text.IndexOf('.') > -1)){
e.Handled = true;
}
}
}
}
我嘗試了以下方法來獲得特定的 31.75 美元。 您需要使用 1.296 作為將英鎊轉換為美元的匯率。
decimal US_Dollars = 1.296m;
Console.WriteLine("$" + string.Format("{0:0.00}", (decimal)24.50 * US_Dollars));
// output: $31.75
在您的代碼中,您將使用以下內容
if (cmbcurrency.Text == "USD")
{
txtresult.Text = System.Convert.ToString("$" + string.Format("{0:0.00}", British_Pound * US_Dollars));
}
建議:使用 web api 來拉取匯率,而不是硬編碼轉換數字。 這是一個例子:
這段代碼是使用API獲取正確的轉化率
public static double GetRate(string baseFormat, string resultFormat)
{
RestClient client = new RestClient($"https://api.exchangeratesapi.io/latest?base={baseFormat}"); // CHange the base to whichever you are converting
RestRequest request = new RestRequest(Method.GET);
request.AddHeader("Accept", "*/*");
var response = client.Execute(request);
var rates = JObject.Parse(response.Content)["rates"];
return double.Parse(rates[resultFormat].ToString());
}
//Usage
double US_Dollars = GetRate("GBP", "USD");
Console.WriteLine("$" + string.Format("{0:0.00}", (double)24.50 * US_Dollars));
// output: $31.74
您需要做的是獲取轉換后的數字並使用 String.Format,如下所示:
String.Format("{0:0.00}", 123.4567);
第一個參數是您想要的格式,第二個參數是您想要轉換為給定格式的值。
我想這就是你需要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.