File tree Expand file tree Collapse file tree 2 files changed +58
-0
lines changed
core-kotlin-modules/core-kotlin-numbers/src
main/kotlin/com/baeldung/percentage
test/kotlin/com/baeldung/percentage Expand file tree Collapse file tree 2 files changed +58
-0
lines changed Original file line number Diff line number Diff line change
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 number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments