Updated on 2026-08-14

This commit is contained in:
Tangem 2026-05-08 05:45:30 -07:00
parent a4e8e059a7
commit 0d8970b386
4 changed files with 70 additions and 6 deletions

View file

@ -242,6 +242,33 @@ fun BigDecimalFiatFormat.anyDecimals(decimals: Int): BigDecimalFormat = BigDecim
.replace(formatterCurrency.getSymbol(locale), fiatCurrencySymbol)
}
/**
* Formats fiat amount following the pattern:
*
* 123 -> $123
*
* 123.1 -> $123.10
*
* 123.10 -> $123.10
*
* 123.456 -> $123.46
*/
fun BigDecimalFiatFormat.optionalDecimals(): BigDecimalFormat = BigDecimalFormat { value ->
val formatterCurrency = getJavaCurrencyByCode(fiatCurrencyCode)
val hasFraction = value.stripTrailingZeros().scale() > 0
val defaultDigits = formatterCurrency.defaultFractionDigits
val formatter = NumberFormat.getCurrencyInstance(locale).apply {
currency = formatterCurrency
minimumFractionDigits = if (hasFraction) defaultDigits else 0
maximumFractionDigits = defaultDigits
roundingMode = RoundingMode.HALF_UP
}
formatter.format(value)
.replace(formatterCurrency.getSymbol(locale), fiatCurrencySymbol)
}
// == Helpers ==
private fun BigDecimal.isLessThanThreshold() = this > BigDecimal.ZERO && this < FIAT_FORMAT_THRESHOLD

View file

@ -2,6 +2,9 @@ package com.tangem.core.ui.format.bigdecimal
import com.google.common.truth.Truth
import org.junit.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.math.BigDecimal
import java.util.Locale
@ -342,4 +345,37 @@ internal class BigDecimalFiatFormatTest {
Truth.assertThat(formatted)
.isEqualTo("-" + "0.50".addUsdSymbolLeft())
}
@ParameterizedTest
@MethodSource("provideTestCasesForOptionalDecimals")
fun `GIVEN amount WHEN format with optionalDecimals THEN correct answer`(
amount: String,
answer: String,
) {
val testValue = BigDecimal(amount)
val formatted = testValue.format {
fiat(
fiatCurrencyCode = usdCurrencyCode,
fiatCurrencySymbol = usdSymbol,
locale = testLocale,
).optionalDecimals()
}
Truth.assertThat(formatted).isEqualTo(answer)
}
private companion object {
@JvmStatic
fun provideTestCasesForOptionalDecimals() = listOf(
Arguments.of("123", "$123"),
Arguments.of("123.1", "$123.10"),
Arguments.of("123.10", "$123.10"),
Arguments.of("123.456", "$123.46"),
Arguments.of("0", "$0"),
Arguments.of("0.1", "$0.10"),
Arguments.of("0.12", "$0.12"),
Arguments.of("0.127", "$0.13"),
)
}
}