1
+ package thousandsSeparator
2
+
3
+ import org.junit.jupiter.api.Test
4
+ import java.text.DecimalFormatSymbols
5
+ import java.text.NumberFormat
6
+ import java.util.*
7
+ import kotlin.test.assertEquals
8
+
9
+ class ParseStringWithThousandsSeparator {
10
+
11
+ @Test
12
+ fun `parses string with thousands separator using replace method` (){
13
+ val result1 = parseStringUsingReplace(" 1,000" , Locale .US )
14
+ val result2 = parseStringUsingReplace(" 25.750" , Locale .GERMAN )
15
+
16
+ assertEquals(1000 , result1)
17
+ assertEquals(25750 , result2)
18
+ }
19
+
20
+ @Test
21
+ fun `parses string with thousands separator using number format class` (){
22
+ val result1 = parseStringWithSeparatorUsingNumberFormat(" 1,000" , Locale .US )
23
+ val result2 = parseStringWithSeparatorUsingNumberFormat(" 25.750" , Locale .GERMAN )
24
+
25
+ assertEquals(1000 , result1)
26
+ assertEquals(25750 , result2)
27
+ }
28
+
29
+ @Test
30
+ fun `parses string with thousands separator using string tokenizer` (){
31
+ val result1 = parseStringUsingTokenizer(" 1,000" , Locale .US )
32
+ val result2 = parseStringUsingTokenizer(" 25.750" , Locale .GERMAN )
33
+
34
+ assertEquals(1000 , result1)
35
+ assertEquals(25750 , result2)
36
+ }
37
+ }
38
+
39
+ fun parseStringUsingReplace (input : String , locale : Locale ): Int {
40
+ val separator = DecimalFormatSymbols .getInstance(locale).groupingSeparator
41
+ return input.replace(Regex (" [$separator ]" ), " " ).toInt()
42
+ }
43
+
44
+ fun parseStringWithSeparatorUsingNumberFormat (input : String , locale : Locale ): Int {
45
+ val number = NumberFormat .getInstance(locale)
46
+ val num = number.parse(input)
47
+ return num.toInt()
48
+ }
49
+
50
+ fun parseStringUsingTokenizer (input : String , locale : Locale ): Int {
51
+ val separator = DecimalFormatSymbols .getInstance(locale).groupingSeparator
52
+ val tokenizer = StringTokenizer (input, separator.toString())
53
+ val builder = StringBuilder ()
54
+ while (tokenizer.hasMoreTokens()) {
55
+ builder.append(tokenizer.nextToken())
56
+ }
57
+ return builder.toString().toInt()
58
+ }
0 commit comments