Added toCurrency
This commit is contained in:
parent
94193e34ed
commit
2590fe67b8
4 changed files with 33 additions and 1 deletions
|
@ -47,6 +47,12 @@ CryptoPrice(val base: String, val currency: String, val amount: Double)
|
|||
```
|
||||
The parameter names match the [Coinbase API](https://developers.coinbase.com/api/v2#get-spot-price).
|
||||
|
||||
To display the amount as a fomatted currency use the `toCurrency` function:
|
||||
|
||||
```kotlin
|
||||
val price = CryptoPrice("BTC", "EUR", 12345.67)
|
||||
println(price.toCurrency()) // will print €12,345.67
|
||||
```
|
||||
### Extending
|
||||
|
||||
A generic `apiCall()` function is available to access other [API data endpoints](https://developers.coinbase.com/api/v2#data-endpoints). For example to retried the current [buy price](https://developers.coinbase.com/api/v2#get-buy-price) of a cryptocurrency:
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
plugins {
|
||||
id("org.jetbrains.kotlin.jvm") version "1.5.0"
|
||||
id("org.jetbrains.kotlin.jvm") version "1.5.10"
|
||||
id("com.github.ben-manes.versions") version "0.38.0"
|
||||
application
|
||||
}
|
||||
|
|
|
@ -38,7 +38,9 @@ import okhttp3.Request
|
|||
import org.json.JSONException
|
||||
import org.json.JSONObject
|
||||
import java.io.IOException
|
||||
import java.text.NumberFormat
|
||||
import java.time.LocalDate
|
||||
import java.util.Currency
|
||||
|
||||
/**
|
||||
* A small Kotlin/Java library for retrieving cryptocurrencies current market prices.
|
||||
|
@ -134,4 +136,15 @@ open class CryptoPrice(val base: String, val currency: String, val amount: Doubl
|
|||
return body.toPrice()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the [amount] as a currency formatted string. (eg: $1,203.33)
|
||||
*/
|
||||
@Throws(IllegalArgumentException::class)
|
||||
fun toCurrency(): String {
|
||||
return NumberFormat.getCurrencyInstance().let {
|
||||
it.setCurrency(Currency.getInstance(currency))
|
||||
it.format(amount)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -80,6 +80,19 @@ class CryptoPriceTest {
|
|||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
@Throws(IllegalArgumentException::class)
|
||||
fun testToCurrency() {
|
||||
val eur = CryptoPrice("BTC", "EUR", 12345.67)
|
||||
assertEquals(eur.toCurrency(), "€12,345.67", "EUR format")
|
||||
|
||||
val gbp = CryptoPrice("ETH", "GBP", 12345.67)
|
||||
assertEquals(gbp.toCurrency(), "£12,345.67", "GBP format")
|
||||
|
||||
val aud = CryptoPrice("BTC", "AUD", 12345.67)
|
||||
assertEquals(aud.toCurrency(), "A$12,345.67", "AUD format")
|
||||
}
|
||||
|
||||
@Test
|
||||
@Throws(CryptoException::class)
|
||||
fun testToPrice() {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue