Skip to content

Commit

Permalink
fix square#1919 Small double values are set to zero in %L translation
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielGronau committed Jun 5, 2024
1 parent d2090c3 commit 5090e22
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import java.text.DecimalFormat
import java.text.DecimalFormatSymbols
import javax.lang.model.element.Element
import javax.lang.model.type.TypeMirror
import kotlin.math.max
import kotlin.reflect.KClass

/**
Expand Down Expand Up @@ -374,7 +375,11 @@ public class CodeBlock private constructor(
minusSign = '-'
}

val precision = if (o is Float || o is Double) o.toString().split(".").last().length else 0
val precision = when(o) {
is Float -> max(o.toBigDecimal().stripTrailingZeros().scale(), 1)
is Double -> max(o.toBigDecimal().stripTrailingZeros().scale(), 1)
else -> 0
}

val pattern = when (o) {
is Float, is Double -> "###,##0.0" + "#".repeat(precision - 1)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,43 @@ class CodeBlockTest {
assertThat(a.toString()).isEqualTo("delicious taco")
}

@Test fun doublePrecision() {
val doubles = listOf(
12345678900000.0 to "12_345_678_900_000.0",
12345678900000.07 to "12_345_678_900_000.07",
123456.0 to "123_456.0",
1234.5678 to "1_234.5678",
12.345678 to "12.345678",
0.12345678 to "0.12345678",
0.0001 to "0.0001",
0.00001 to "0.00001",
0.000001 to "0.000001",
0.0000001 to "0.0000001",
)
for((d, expected) in doubles) {
val a = CodeBlock.of("number %L", d)
assertThat(a.toString()).isEqualTo("number $expected")
}
}

@Test fun floatPrecision() {
val floats = listOf(
12345678.0f to "12_345_678.0",
123456.0f to "123_456.0",
1234.567f to "1_234.567",
12.34567f to "12.34567",
0.1234567f to "0.1234567",
0.0001f to "0.0001",
0.00001f to "0.00001",
0.000001f to "0.000001",
0.0000001f to "0.0000001",
)
for((f, expected) in floats) {
val a = CodeBlock.of("number %L", f)
assertThat(a.toString()).isEqualTo("number $expected")
}
}

@Test fun percentEscapeCannotBeIndexed() {
assertThrows<IllegalArgumentException> {
CodeBlock.builder().add("%1%", "taco").build()
Expand Down

0 comments on commit 5090e22

Please sign in to comment.