Sohail Arif
Sohail Arif

Reputation: 13

How do you round a decimal number in C sharp?

I am trying to write some code that converts Pound Sterling to US Dollars. The converter tool works fine. However, I am struggling with rounding the decimal numbers. So for example, when I convert £24.50, my tool outputs $31.8500 when I want it to output $31.75. I have experimented with the Math.Round(); method but unfortunately I haven't failed to get my desired result.

Here is my code, what am I doing wrong?

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;
        }

    }
}
}

Upvotes: 0

Views: 109

Answers (2)

Jawad
Jawad

Reputation: 11364

I tried the following to get the specific $31.75. You will need to use 1.296 as the rate to convert pound to USD.

    decimal US_Dollars = 1.296m;

    Console.WriteLine("$" + string.Format("{0:0.00}", (decimal)24.50 * US_Dollars));
    // output: $31.75

In your code, you will use the following

    if (cmbcurrency.Text == "USD")
    {
        txtresult.Text = System.Convert.ToString("$" + string.Format("{0:0.00}", British_Pound * US_Dollars));
    }

Recommendation: Use a web api to pull the rate instead of hardcoding the number for conversion. This is one example:

This code is to use the API to get the correct conversion rate

    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

Upvotes: 1

Jasc24
Jasc24

Reputation: 150

What you need to do, is to take your converted number and use String.Format, something like this:

String.Format("{0:0.00}", 123.4567); 

First parameter is the format you would like to have, and the second one is the value you want to translate to the given format.

I guess this is what you need.

Upvotes: 0

Related Questions