Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Chuyển đổi tiền tệ (Currency Conversion) trong C#

Chuyển đổi tiền tệ đơn giản: nhân số lượng với tỷ giá. Thực tế cần API tỷ giá real-time, xử lý làm tròn, culture formatting.

Ví dụ cơ bản

using System;
using System.Globalization;

class Program
{
    static void Main()
    {
        double usdAmount = 10;
        double exchangeRate = 69; // 1 USD = 69 INR (ví dụ)
        
        double inrAmount = usdAmount * exchangeRate;
        
        Console.WriteLine($"{usdAmount} USD = {inrAmount} INR");
        
        // Format tiền tệ đúng chuẩn
        CultureInfo vietnam = new CultureInfo("vi-VN");
        CultureInfo usa = new CultureInfo("en-US");
        
        Console.WriteLine($"Vietnam: {inrAmount.ToString("C0", vietnam)}"); // ₫690
        Console.WriteLine($"US: {usdAmount.ToString("C2", usa)}");         // $10.00
    }
}

Kết quả đầu ra

10 USD = 690 INR
Vietnam: ₫690
US: $10.00

Ứng dụng thực tế: Dùng API tỷ giá

using System.Net.Http;
using System.Text.Json;

class CurrencyConverter
{
    private static readonly HttpClient _http = new HttpClient();
    
    public static async Task ConvertAsync(decimal amount, string from, string to)
    {
        // Ví dụ: exchangerate-api.com (cần API key)
        string url = $"https://api.exchangerate-api.com/v4/latest/{from}";
        var response = await _http.GetStringAsync(url);
        
        using var doc = JsonDocument.Parse(response);
        decimal rate = doc.RootElement.GetProperty("rates").GetProperty(to).GetDecimal();
        
        return amount * rate;
    }
}

Lưu ý: Code gốc hardcode tỷ giá 69. Thực tế dùng API (exchangerate-api, fixer.io, v.v.), cache tỷ giá, xử lý decimal precision (không dùng double cho tiền), rounding mode.