Skip to content

Commit

Permalink
[#1455] Remove hard-coded currency decimal sep
Browse files Browse the repository at this point in the history
Closes #1455
  • Loading branch information
HonzaR committed Apr 23, 2024
1 parent b29e1a3 commit e75123d
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 6 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ and this library adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Android Gradle Plugin 8.3.0
- Kotlin 1.9.23
- Other dependencies update
- `safelyConvertToBigDecimal()` API from `CurrencyFormatter.kt` now excepts decimal separator Char on input

## [2.1.0] - 2024-04-09

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -334,14 +334,14 @@ fun BigDecimal.convertCurrency(
*
* @return this string as a BigDecimal or null when parsing fails.
*/
fun String?.safelyConvertToBigDecimal(): BigDecimal? {
fun String?.safelyConvertToBigDecimal(decimalSeparator: Char): BigDecimal? {
if (this.isNullOrEmpty()) {
return BigDecimal.ZERO
}
val result =
try {
// ignore commas and whitespace
val sanitizedInput = this.filter { it.isDigit() or (it == '.') }
val sanitizedInput = this.filter { it.isDigit() or (it == decimalSeparator) }
BigDecimal.ZERO.max(BigDecimal(sanitizedInput, MathContext.DECIMAL128))
} catch (nfe: NumberFormatException) {
Twig.debug(nfe) { "Exception while converting String to BigDecimal" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,17 +82,17 @@ class ConversionsTest {

@Test
fun `toZec reduces precision`() {
val amount = "20.37905033625433054819645404524149".safelyConvertToBigDecimal()
val expected = "20.379050".safelyConvertToBigDecimal()
val amount = "20.37905033625433054819645404524149".safelyConvertToBigDecimal('.')
val expected = "20.379050".safelyConvertToBigDecimal('.')
assertEquals(expected, amount.toZec(6))
assertEquals("20.37905", amount.toZecString(6))
}

@Test
fun `convert usd to zec`() {
val price = BigDecimal("49.07", MathContext.DECIMAL128)
val usdValue = "1000".safelyConvertToBigDecimal()
val usdValue = "1000".safelyConvertToBigDecimal('.')
val zecValue = usdValue.convertUsdToZec(price)
assertEquals("20.379050".safelyConvertToBigDecimal(), zecValue.toZec(6))
assertEquals("20.379050".safelyConvertToBigDecimal('.'), zecValue.toZec(6))
}
}

0 comments on commit e75123d

Please sign in to comment.