diff --git a/core-java/src/main/java/com/baeldung/string/DoubleToString.java b/core-java/src/main/java/com/baeldung/string/DoubleToString.java new file mode 100644 index 0000000000..d26d26f3df --- /dev/null +++ b/core-java/src/main/java/com/baeldung/string/DoubleToString.java @@ -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); + } + +} diff --git a/core-java/src/test/java/com/baeldung/string/DoubleToStringUnitTest.java b/core-java/src/test/java/com/baeldung/string/DoubleToStringUnitTest.java new file mode 100644 index 0000000000..5212d7aa1a --- /dev/null +++ b/core-java/src/test/java/com/baeldung/string/DoubleToStringUnitTest.java @@ -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); + } + + +}