Double output in java
I have:
double s1 = 2.0;
double s2 = 2.3;
double s3 = 2.33,
double s4 = 2.333;
It is required that when displaying the results on the screen:
s1 = 2
s2 = 2.3
s3 = 2.33
s4 = 2.333
The problem is that you need to use one function to all the numbers.
3
2 answers
Formatting Numeric Print Output
Code on ideone.com
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
double s1 = 2.0;
double s2 = 2.3;
double s3 = 2.33;
double s4 = 2.333;
System.out.format("s1 = %.0f%n", s1);
System.out.format("s2 = %.1f%n", s2);
System.out.format("s3 = %.2f%n", s3);
System.out.format("s4 = %.3f%n", s4);
System.out.format("s1 = %.0f; s2 = %.1f; s3 = %.2f; s4 = %.3f", s1, s2, s3, s4);
}
}
8
Author: Opalosolo, 2015-12-10 15:25:49
Thank you, I found it myself already) 10 times I went to the first link, but did not read to the end) Here is the code that solved my problem.
import java.text.*;
public class DecimalFormatDemo {
static public void customFormat(String pattern, double value ) {
DecimalFormat myFormatter = new DecimalFormat(pattern);
String output = myFormatter.format(value);
System.out.println(value + " " + pattern + " " + output);
}
static public void main(String[] args) {
customFormat("###,###.###", 123.0);
customFormat("###,###.###", 123.120);
customFormat("###,###.######", 123.0);
customFormat("###,###.######, 123.123120);
}
}
Result:
123
123,12
123
123,12312
3
Author: tsvik dima, 2013-09-30 17:16:04