Core Java

How to Convert Double to String in Java

In this article, we will learn how to Convert Double to String in Java.

1. Introduction

Java language provides a Double and String types. A java.lang.Double class represents a floating-point number and java.lang.String class represents a sequence of characters. In this example, I will demonstrate how to convert a Double to String by utilizing the following classes:

double to string java
  • java.lang.Double
  • java.lang.String
  • java.text.DecimalFormat
  • java.lang.StringBuffer
  • java.lang.StringBuilder.

2. Technologies Used

The example code in this article was built and run using:

  • Java 11
  • Maven 3.3.9
  • Eclipse Oxygen
  • Junit 4.12

3. Maven Project

3.1 Dependencies

I will include Junit in the pom.xml.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>jcg-zheng-demo</groupId>
	<artifactId>doubleToString-demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<build>
		<sourceDirectory>src</sourceDirectory>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.8.0</version>
				<configuration>
					<release>11</release>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.12</version>
		</dependency>
	</dependencies>
</project>

4. JUnit Tests

I will create five test classes to demonstrate how to convert a Double to String.

4.1 DoubleTest

The java.lang.Double class has two methods to convert a double to String.

  • String toString() – Returns a string representation of this Double object.
  • static String toString​(double d) – Returns a string representation of the double argument.

In this step, I will create a DoubleTest class with four test methods.

DoubleTest.java

package jcg.zheng.demo;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class DoubleTest {

	private Double largeDouble = Double.valueOf(1234567890123456.789);

	private Double smallDouble = Double.valueOf(12.345);

	@Test
	public void convertDoubleToString_via_toString_large() {
		// Large number is with scientific notation
		String dString = largeDouble.toString();
		assertEquals("1.2345678901234568E15", dString);
	}
	
	@Test
	public void convertDoubleToString_via_toString_large_1() {
		// Large number is with scientific notation
		String dString = Double.toString(largeDouble.doubleValue());
		assertEquals("1.2345678901234568E15", dString);
	}

	@Test
	public void convertDoubleToString_via_toString_small() {
		String dString = smallDouble.toString();
		assertEquals("12.345", dString);
	}
	
	@Test
	public void convertDoubleToString_via_toString_small_1() {
		String dString = Double.toString(smallDouble.doubleValue());
		assertEquals("12.345", dString);
	}

}

Execute it as a Junit test and capture the output here.

mvn test -Dtest=DoubleTest

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running jcg.zheng.demo.DoubleTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.144 sec

Results :

Tests run: 4, Failures: 0, Errors: 0, Skipped: 0

4.2 StringTest

The java.lang.String class includes two methods to convert a double to String.

  • static String format​(String format, Object... args) – Returns a formatted string using the specified format string and arguments. The formatting pattern for converting a double to String is %[argument_index$][flags][width][.precision]f.
  • static String valueOf​(double d) – Returns the string representation of the double argument. The representation is exactly the one returned by the Double.toString method of one argument.

In this step, I will create a StringTest class with eight methods.

StringTest.java

package jcg.zheng.demo;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class StringTest {

	private Double largeDouble = Double.valueOf(1234567890123456.789);

	private Double smallDouble = Double.valueOf(12.345);

	@Test
	public void convertDoubleToString_via_format_large_0() {
		String dString = String.format("%#.1f", largeDouble);
		assertEquals("1234567890123456.8", dString);
	}

	@Test
	public void convertDoubleToString_via_format_large_1() {
		String dString = String.format("%025.2f", largeDouble);
		assertEquals("0000001234567890123456.80", dString);
	}

	@Test
	public void convertDoubleToString_via_format_large_2() {
		String dString = String.format("%+.3f", largeDouble);
		assertEquals("+1234567890123456.800", dString);
	}

	@Test
	public void convertDoubleToString_via_format_small() {
		String dString = String.format("%.3f", smallDouble);
		assertEquals("12.345", dString);
	}

	@Test
	public void convertDoubleToString_via_format_small_1() {
		String dString = String.format("%.2f", smallDouble);
		assertEquals("12.35", dString);
	}

	@Test
	public void convertDoubleToString_via_format_small_2() {
		String dString = String.format("%.1f", smallDouble);
		assertEquals("12.3", dString);
	}

	@Test
	public void convertDoubleToString_via_valueOf_large() {
		// Large number is with scientific notation
		String dString = String.valueOf(largeDouble);
		assertEquals("1.2345678901234568E15", dString);
	}

	@Test
	public void convertDoubleToString_via_valueOf_small() {
		String dString = String.valueOf(smallDouble);
		assertEquals("12.345", dString);
	}

}

Execute it as a Junit test and capture the output here.

mvn test -Dtest=StringTest

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running jcg.zheng.demo.StringTest
Tests run: 8, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.143 sec

Results :

Tests run: 8, Failures: 0, Errors: 0, Skipped: 0

4.3 DecimalFormatTest

The java.text.DecimalFormat class provides a method to format a Double into a String with the formatting pattern. Here are common formatting characters:

  • 0 – prints a digit if provided, 0 otherwise
  • # – prints a digit if provided, nothing otherwise
  • . – indicates where to put the decimal separator
  • , – indicates where to put the grouping separator
  • E – represents the exponent of ten

Please click here to see the completed formatting characters.

  • StringBuffer format​(double number, StringBuffer result, FieldPosition fieldPosition) – Formats a double to produce a string.

In this step, I will create a DecimalFormatTest class with five methods.

DecimalFormatTest.java

package jcg.zheng.demo;

import static org.junit.Assert.assertEquals;

import java.text.DecimalFormat;

import org.junit.Test;

/**
 * Pattern 0 – prints a digit if provided, 0 otherwise # – prints a digit if
 * provided, nothing otherwise . – indicate where to put the decimal separator ,
 * – indicate where to put the grouping separator
 *
 */
public class DecimalFormatTest {

	private Double largeDouble = Double.valueOf(1234567890123456.789);

	private Double smallDouble = Double.valueOf(12.345);

	@Test
	public void convertDoubleToString_via_format_pattern_1() {
		String formatPattern = "###,###.###";
		DecimalFormat decimalFormat = new DecimalFormat(formatPattern);

		String dString = decimalFormat.format(smallDouble);

		assertEquals("12.345", dString);

	}

	@Test
	public void convertDoubleToString_via_format_pattern_2() {
		String formatPattern = "000,000.0000";
		DecimalFormat decimalFormat = new DecimalFormat(formatPattern);

		String dString = decimalFormat.format(smallDouble);

		assertEquals("000,012.3450", dString);
	}

	@Test
	public void convertDoubleToString_via_format_pattern_3() {
		String formatPattern = "Some Value ###,###.#";
		DecimalFormat decimalFormat = new DecimalFormat(formatPattern);

		String dString = decimalFormat.format(smallDouble);

		assertEquals("Some Value 12.3", dString);
	}

	@Test
	public void convertDoubleToString_via_format_pattern_4() {
		String formatPattern = "###,###,###,###,###,###.#";
		DecimalFormat decimalFormat = new DecimalFormat(formatPattern);

		String dString = decimalFormat.format(largeDouble);

		assertEquals("1,234,567,890,123,456.8", dString);
	}

	@Test
	public void convertDoubleToString_via_format_pattern_5() {
		String formatPattern = "00000000000E0";
		DecimalFormat decimalFormat = new DecimalFormat(formatPattern);

		String dString = decimalFormat.format(largeDouble);

		assertEquals("12345678901E5", dString);
	}

}

Execute it as a Junit test and capture the output here.

mvn test -Dtest=DecimalFormatTest

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running jcg.zheng.demo.DecimalFormatTest
Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.297 sec

Results :

Tests run: 5, Failures: 0, Errors: 0, Skipped: 0

4.4 StringBufferTest

The java.lang.StringBuffer class has the append method to convert a double into a StringBuffer.

  • StringBuffer append​(double d) – Appends the string representation of the double argument to this sequence. The overall effect is exactly as if the argument were converted to a string by the method String.valueOf(double), and the characters of that string were then appended to this character sequence.

In this step, I will create a StringBufferTest class with two tests.

StringBufferTest.java

package jcg.zheng.demo;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Test;

public class StringBufferTest {

	private Double largeDouble = Double.valueOf(1234567890123456.789);

	private StringBuffer sb;

	private Double smallDouble = Double.valueOf(12.345);

	@Before
	public void setup() {
		sb = new StringBuffer();
	}

	@Test
	public void convertDoubleToString_via_append_large() {
		sb.append(largeDouble);
		// Large number is with scientific notation
		String dString = sb.toString();
		assertEquals("1.2345678901234568E15", dString);
	}

	@Test
	public void convertDoubleToString_via_append_small() {
		sb.append(smallDouble);
		String dString = sb.toString();
		assertEquals("12.345", dString);
	}

}

Execute it as a Junit test and capture the output here.

mvn test -Dtest=StringBufferTest

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running jcg.zheng.demo.StringBufferTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.137 sec

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

4.5 StringBuilderTest

The java.lang.StringBuilder has the append method to convert a double into a StringBuilder.

  • StringBuilder append​(double d) – Appends the string representation of the double argument to this sequence. The overall effect is exactly as if the argument were converted to a string by the method String.valueOf(double), and the characters of that string were then appended to this character sequence.

In this step, I will create a StringBuilderTest class with two tests.

StringBuilderTest.java

package jcg.zheng.demo;

import static org.junit.Assert.assertEquals;

import org.junit.Before;
import org.junit.Test;

public class StringBuilderTest {

	private Double largeDouble = Double.valueOf(1234567890123456.789);

	private StringBuilder sb;

	private Double smallDouble = Double.valueOf(12.345);

	@Before
	public void setup() {
		sb = new StringBuilder();
	}

	@Test
	public void convertDoubleToString_via_append_large() {
		sb.append(largeDouble);
		// Large number is with scientific notation
		String dString = sb.toString();
		assertEquals("1.2345678901234568E15", dString);
	}

	@Test
	public void convertDoubleToString_via_append_small() {
		sb.append(smallDouble);
		String dString = sb.toString();
		assertEquals("12.345", dString);
	}

}

Execute it as a Junit test and capture the output here.

mvn test -Dtest=StringBuilderTest

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running jcg.zheng.demo.StringBuilderTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.188 sec

Results :

Tests run: 2, Failures: 0, Errors: 0, Skipped: 0

5. Summary

In this example, I showed how to convert a Double to String by utilizing Java’s five classes: Double, String, DecimalFormat, StringBuffer, and StringBuilder.

6. Download the Source Code

In this article, we learned how to Convert a Double to String in Java.

Download
You can download the full source code of this example here: How to Convert Double to String in Java

Mary Zheng

Mary has graduated from Mechanical Engineering department at ShangHai JiaoTong University. She also holds a Master degree in Computer Science from Webster University. During her studies she has been involved with a large number of projects ranging from programming and software engineering. She works as a senior Software Engineer in the telecommunications sector where she acts as a leader and works with others to design, implement, and monitor the software solution.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button