2020-06-29 04:44:35 +02:00
|
|
|
using System;
|
2018-03-25 18:57:44 +02:00
|
|
|
using System.Globalization;
|
|
|
|
using System.Text.RegularExpressions;
|
|
|
|
using BTCPayServer.Services.Rates;
|
|
|
|
|
|
|
|
namespace BTCPayServer
|
|
|
|
{
|
|
|
|
public class CurrencyValue
|
|
|
|
{
|
2020-06-29 05:07:48 +02:00
|
|
|
static readonly Regex _Regex = new Regex("^([0-9]+(\\.[0-9]+)?)\\s*([a-zA-Z]+)$");
|
2018-03-25 18:57:44 +02:00
|
|
|
public static bool TryParse(string str, out CurrencyValue value)
|
|
|
|
{
|
|
|
|
value = null;
|
2020-12-29 09:58:35 +01:00
|
|
|
if (string.IsNullOrEmpty(str))
|
|
|
|
{
|
|
|
|
return false;
|
|
|
|
}
|
2018-03-25 18:57:44 +02:00
|
|
|
var match = _Regex.Match(str);
|
|
|
|
if (!match.Success ||
|
2021-10-21 12:15:02 +02:00
|
|
|
!decimal.TryParse(match.Groups[1].Value, NumberStyles.Any, CultureInfo.InvariantCulture, out var v))
|
2018-03-25 18:57:44 +02:00
|
|
|
return false;
|
|
|
|
|
2019-10-03 11:00:07 +02:00
|
|
|
var currency = match.Groups[match.Groups.Count - 1].Value.ToUpperInvariant();
|
2020-05-31 12:18:29 +02:00
|
|
|
var currencyData = CurrencyNameTable.Instance.GetCurrencyData(currency, false);
|
2018-03-25 18:57:44 +02:00
|
|
|
if (currencyData == null)
|
|
|
|
return false;
|
|
|
|
v = Math.Round(v, currencyData.Divisibility);
|
|
|
|
value = new CurrencyValue()
|
|
|
|
{
|
|
|
|
Value = v,
|
|
|
|
Currency = currency
|
|
|
|
};
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
public decimal Value { get; set; }
|
|
|
|
public string Currency { get; set; }
|
|
|
|
|
|
|
|
public override string ToString()
|
|
|
|
{
|
|
|
|
return Value.ToString(CultureInfo.InvariantCulture) + " " + Currency;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|