39 lines
1.2 KiB
Go
39 lines
1.2 KiB
Go
![]() |
package utils
|
|||
|
|
|||
|
import (
|
|||
|
"fmt"
|
|||
|
"math"
|
|||
|
|
|||
|
"github.com/danilsolovyov/croupierCbrf/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
|
|||
|
}
|