Wednesday 22 April 2020

Convert Double to String

Approach 1: Concatenate empty string
String str1 = d1 + "";

Approach2: Use Double.toString
String str2 = Double.toString(d1);

Approach 3: Use String.valueOf
String str3 = String.valueOf(d1);

Approach 4: Use DecimalFormat
DecimalFormat decimalFormat = new DecimalFormat("#,##0.000000");
String str4 = decimalFormat.format(d1);

App.java
package com.sample.app;

import java.text.DecimalFormat;

public class App {

	public static void main(String args[]) {

		Double d1 = 2.35765391;

		// Approach 1
		String str1 = d1 + "";

		// Approach2
		String str2 = Double.toString(d1);

		// Approach 3
		String str3 = String.valueOf(d1);

		// Approach 4
		DecimalFormat decimalFormat = new DecimalFormat("#,##0.000000");
		String str4 = decimalFormat.format(d1);

		System.out.println("d1 : " + d1);
		System.out.println("str1 : " + str1);
		System.out.println("str2 : " + str2);
		System.out.println("str3 : " + str3);
		System.out.println("str4 : " + str4);

	}

}

Output
d1 : 2.35765391
str1 : 2.35765391
str2 : 2.35765391
str3 : 2.35765391
str4 : 2.357654



You may like

No comments:

Post a Comment