cbrfWorker/internal/utils/currency_exchange.go
2023-06-22 11:26:42 +03:00

39 lines
1.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package utils
import (
"fmt"
"math"
"github.com/danilsolovyov/croupierCbrf/internal/dal"
)
func CurrencyExchange(currencies map[string]dal.Quote, fromCurrency, toCurrency string, amount int64) (int64, error) {
fromRate, ok := currencies[fromCurrency]
if !ok && fromCurrency != dal.DefaultCurrency {
return 0, fmt.Errorf("Курс для валюты %s не найден", fromCurrency)
}
if fromCurrency == dal.DefaultCurrency {
fromRate.Value = 1
}
toRate, ok := currencies[toCurrency]
if !ok && toCurrency != dal.DefaultCurrency {
return 0, fmt.Errorf("Курс для валюты %s не найден", toCurrency)
}
if toCurrency == dal.DefaultCurrency {
toRate.Value = 1
}
// Округляем число курса 79.9093 => 79.91
roundedFromValue := math.Round(fromRate.Value*100) / 100
roundedToValue := math.Round(toRate.Value*100) / 100
// Переводим сумму из одной валюты в рубли
amountInRubles := float64(amount) * roundedFromValue
// Переводим рубли в нужную валюту и округляем до ближайшего целого числа
result := int64(amountInRubles / roundedToValue)
return result, nil
}