Skip to content

Commit eafa3b8

Browse files
authored
[KTLN-809] Add Samples (#826)
1 parent e8b464c commit eafa3b8

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
package com.baeldung.percentage
2+
3+
import java.math.BigDecimal
4+
import java.math.RoundingMode
5+
6+
fun Number.divideToPercent(divideTo: Number): Double {
7+
if (divideTo.toDouble() == 0.0) return 0.0
8+
return (this.toDouble() / divideTo.toDouble()) * 100.0
9+
}
10+
11+
infix fun Number.percentOf(value: Number): Double {
12+
return if (this.toDouble() == 0.0) 0.0
13+
else (value.toDouble() / this.toDouble())
14+
}
15+
16+
fun BigDecimal.percentOf(total: BigDecimal): BigDecimal {
17+
return if (total == BigDecimal.ZERO) BigDecimal.ZERO
18+
else this.divide(total, 5, RoundingMode.HALF_UP) * BigDecimal(100)
19+
}
20+
21+
fun Number.formatPercent() = "$this%"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package com.baeldung.percentage
2+
3+
import org.junit.jupiter.api.Assertions.assertEquals
4+
import org.junit.jupiter.api.Assertions.assertTrue
5+
import org.junit.jupiter.api.Test
6+
import java.math.BigDecimal
7+
8+
class CalculatePercentageUnitTest {
9+
@Test
10+
fun `should return accurate division result`() {
11+
val count = 5
12+
val totalCount = 10
13+
val expected = 50.0
14+
val result = (count.toDouble() / totalCount.toDouble()) * 100.0
15+
assertEquals(expected, result)
16+
}
17+
18+
@Test
19+
fun `when dividing 10 by 20, should return 50`() {
20+
val result = 10.divideToPercent(20)
21+
assertEquals(50.0, result)
22+
}
23+
24+
@Test
25+
fun `when using infix function, 10 percentOf 200 should return 20`() {
26+
val result = 10 percentOf 200
27+
assertEquals(20.0, result)
28+
}
29+
30+
@Test fun `calculate percentage using BigDecimal for high precision`() {
31+
val part = BigDecimal("25")
32+
val whole = BigDecimal("200")
33+
val expectedPercentage = BigDecimal("12.50") // Expecting 12.50% as the result
34+
val resultPercentage = part.percentOf(whole)
35+
assertTrue { resultPercentage.compareTo(expectedPercentage) == 0 }
36+
}
37+
}

0 commit comments

Comments
 (0)