Skip to content

Commit e244269

Browse files
daoireEugen
authored andcommitted
Refactor Code and add Tests (eugenp#5251)
1 parent 75b2ba2 commit e244269

2 files changed

Lines changed: 86 additions & 0 deletions

File tree

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package com.baeldung.string;
2+
3+
import java.math.RoundingMode;
4+
import java.text.DecimalFormat;
5+
import java.text.NumberFormat;
6+
7+
public class DoubleToString {
8+
9+
public static String truncateByCast(double d) {
10+
return String.valueOf((int) d);
11+
}
12+
13+
public static String roundWithStringFormat(double d) {
14+
return String.format("%.0f", d);
15+
}
16+
17+
public static String truncateWithNumberFormat(double d) {
18+
NumberFormat nf = NumberFormat.getInstance();
19+
nf.setMaximumFractionDigits(0);
20+
nf.setRoundingMode(RoundingMode.FLOOR);
21+
return nf.format(d);
22+
}
23+
24+
public static String roundWithNumberFormat(double d) {
25+
NumberFormat nf = NumberFormat.getInstance();
26+
nf.setMaximumFractionDigits(0);
27+
return nf.format(d);
28+
}
29+
30+
public static String truncateWithDecimalFormat(double d) {
31+
DecimalFormat df = new DecimalFormat("#,###");
32+
df.setRoundingMode(RoundingMode.FLOOR);
33+
return df.format(d);
34+
}
35+
36+
public static String roundWithDecimalFormat(double d) {
37+
DecimalFormat df = new DecimalFormat("#,###");
38+
return df.format(d);
39+
}
40+
41+
}
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.baeldung.string;
2+
3+
import static org.assertj.core.api.Assertions.assertThat;
4+
5+
import org.junit.Test;
6+
7+
public class DoubleToStringUnitTest {
8+
9+
private static final double DOUBLE_VALUE = 3.56;
10+
private static final String TRUNCATED_DOUBLE = "3";
11+
private static final String ROUNDED_UP_DOUBLE = "4";
12+
13+
14+
@Test
15+
public void truncateByCastTest() {
16+
assertThat(DoubleToString.truncateByCast(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
17+
}
18+
19+
@Test
20+
public void roundingWithStringFormatTest() {
21+
assertThat(DoubleToString.roundWithStringFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
22+
}
23+
24+
@Test
25+
public void truncateWithNumberFormatTest() {
26+
assertThat(DoubleToString.truncateWithNumberFormat(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
27+
}
28+
29+
@Test
30+
public void roundWithNumberFormatTest() {
31+
assertThat(DoubleToString.roundWithNumberFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
32+
}
33+
34+
@Test
35+
public void truncateWithDecimalFormatTest() {
36+
assertThat(DoubleToString.truncateWithDecimalFormat(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
37+
}
38+
39+
@Test
40+
public void roundWithDecimalFormatTest() {
41+
assertThat(DoubleToString.roundWithDecimalFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
42+
}
43+
44+
45+
}

0 commit comments

Comments
 (0)