Skip to content

Commit 8c48245

Browse files
authored
Added the code for double to string conversion without scientific notation (#859)
* Added the code for double to string conversion without scientific notation * removed println
1 parent 7b05ab7 commit 8c48245

File tree

1 file changed

+71
-0
lines changed

1 file changed

+71
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
package com.baeldung.decimalformat
2+
3+
import org.junit.Test
4+
import java.math.BigDecimal
5+
import java.text.DecimalFormat
6+
import java.text.DecimalFormatSymbols
7+
import java.text.NumberFormat
8+
import java.util.*
9+
import kotlin.test.assertFalse
10+
11+
fun formatDoubleUsingFormat(num: Double): String {
12+
return "%.8f".format(Locale.US, num)
13+
}
14+
15+
fun formatUsingBigDecimal(num: Double): String {
16+
return BigDecimal.valueOf(num).toPlainString()
17+
}
18+
19+
fun formatUsingString(num: Double): String {
20+
return String.format(Locale.US, "%.6f", num)
21+
}
22+
23+
fun formatUsingNumberFormat(num: Double): String {
24+
val numberFormat = NumberFormat.getInstance(Locale.US)
25+
numberFormat.maximumFractionDigits = 8
26+
return numberFormat.format(num)
27+
}
28+
29+
fun formatUsingDecimalFormat(num: Double): String {
30+
val symbols = DecimalFormatSymbols(Locale.US)
31+
val df = DecimalFormat("#.###############", symbols)
32+
return df.format(num)
33+
}
34+
35+
class DecimalFormatUnitTest {
36+
37+
@Test
38+
fun `format double using format method`() {
39+
val num = 0.000123456789
40+
val result = formatDoubleUsingFormat(num)
41+
assertFalse(result.contains("E"))
42+
}
43+
44+
@Test
45+
fun `format double using bigdecimal method`() {
46+
val num: Double = 0.000123456789
47+
val result = formatUsingBigDecimal(num)
48+
assertFalse(result.contains("E"))
49+
}
50+
51+
@Test
52+
fun `format double using DecimalFormat method`() {
53+
val num: Double = 0.000123456789
54+
val result = formatUsingDecimalFormat(num)
55+
assertFalse(result.contains("E"))
56+
}
57+
58+
@Test
59+
fun `format double using String method`() {
60+
val num: Double = 0.000123456789
61+
val result = formatUsingString(num)
62+
assertFalse(result.contains("E"))
63+
}
64+
65+
@Test
66+
fun `format double using NumberFormat method`() {
67+
val num: Double = 0.000123456789
68+
val result = formatUsingNumberFormat(num)
69+
assertFalse(result.contains("E"))
70+
}
71+
}

0 commit comments

Comments
 (0)