Add exchange for currency in money exchange utils

This commit is contained in:
Sambo Chea 2020-08-26 21:44:33 +07:00
parent cb28bc0d6a
commit b93c4ef5ac
3 changed files with 18 additions and 2 deletions

View File

@ -2,7 +2,7 @@ package com.cubetiqs.libra.moneyutils
open class Money(
var value: Double,
var currency: String = "USD"
private var currency: String = "USD"
) : StdMoney {
//////////////////// - PROPERTIES - ////////////////////
@ -20,4 +20,9 @@ open class Money(
override fun toString(): String {
return "Money(value=${getMoneyValue()}, currency='${getMoneyCurrency()}')"
}
companion object {
val ZERO: StdMoney
get() = Money(value = 0.0)
}
}

View File

@ -15,6 +15,8 @@ object MoneyConfig {
* Value is the rate
*/
private val config: MutableMap<String, Double> = mutableMapOf()
private var valid: Boolean = false
fun isValid() = valid
/**
* Money properties for money config format
@ -56,6 +58,9 @@ object MoneyConfig {
throw MoneyCurrencyStateException("money config format is not valid!")
}
}
// validate the config is load or not
this.valid = this.config.isNotEmpty()
}
// all currencies with its rate

View File

@ -1,7 +1,13 @@
package com.cubetiqs.libra.moneyutils
object MoneyExchangeUtils {
fun computeRate(rateFrom: Double, rateTo: Double, baseRate: Double = 1.0, amountFrom: Double = 1.0): Double {
fun exchange(exchangeFrom: StdMoney, exchangeToCurrency: String): StdMoney {
val rateFrom = MoneyConfig.getRate(exchangeFrom.getMoneyCurrency())
val rateTo = MoneyConfig.getRate(exchangeToCurrency)
return Money(value = computeRate(rateFrom, rateTo, amountFrom = exchangeFrom.getMoneyValue()), currency = exchangeToCurrency)
}
private fun computeRate(rateFrom: Double, rateTo: Double, baseRate: Double = 1.0, amountFrom: Double = 1.0): Double {
return amountFrom * ((baseRate / rateFrom) / (baseRate / rateTo))
}
}