Refactor Code and add Tests (#5251)

This commit is contained in:
daoire 2018-10-23 21:09:29 +01:00 committed by Eugen
parent 75b2ba2efa
commit e24426923e
2 changed files with 86 additions and 0 deletions

View File

@ -0,0 +1,41 @@
package com.baeldung.string;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.NumberFormat;
public class DoubleToString {
public static String truncateByCast(double d) {
return String.valueOf((int) d);
}
public static String roundWithStringFormat(double d) {
return String.format("%.0f", d);
}
public static String truncateWithNumberFormat(double d) {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
nf.setRoundingMode(RoundingMode.FLOOR);
return nf.format(d);
}
public static String roundWithNumberFormat(double d) {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(0);
return nf.format(d);
}
public static String truncateWithDecimalFormat(double d) {
DecimalFormat df = new DecimalFormat("#,###");
df.setRoundingMode(RoundingMode.FLOOR);
return df.format(d);
}
public static String roundWithDecimalFormat(double d) {
DecimalFormat df = new DecimalFormat("#,###");
return df.format(d);
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.string;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.Test;
public class DoubleToStringUnitTest {
private static final double DOUBLE_VALUE = 3.56;
private static final String TRUNCATED_DOUBLE = "3";
private static final String ROUNDED_UP_DOUBLE = "4";
@Test
public void truncateByCastTest() {
assertThat(DoubleToString.truncateByCast(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
}
@Test
public void roundingWithStringFormatTest() {
assertThat(DoubleToString.roundWithStringFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
}
@Test
public void truncateWithNumberFormatTest() {
assertThat(DoubleToString.truncateWithNumberFormat(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
}
@Test
public void roundWithNumberFormatTest() {
assertThat(DoubleToString.roundWithNumberFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
}
@Test
public void truncateWithDecimalFormatTest() {
assertThat(DoubleToString.truncateWithDecimalFormat(DOUBLE_VALUE)).isEqualTo(TRUNCATED_DOUBLE);
}
@Test
public void roundWithDecimalFormatTest() {
assertThat(DoubleToString.roundWithDecimalFormat(DOUBLE_VALUE)).isEqualTo(ROUNDED_UP_DOUBLE);
}
}