12
votes

I'm programming a simple java program. I need to get a string from input and divide it into two parts: 1-double 2-string. Then I need to do a simple calculation on the double and send the result to the output with specific precision(4). It works fine, but there is a problem when the input is 0, then it doesn't work properly.

For example for these input, output will be:

1 kg
output:2.2046

3.1 kg
output:6.8343

But when the input is 0, the output should be 0.0000, but it shows 0.0 . What should I do to force it to show 0.0000?

I read similar post about double precision, they suggest something like BigDecimal class, but I can't use them in this case, my code for doing this is:

line=input.nextLine();
array=line.split(" ");
value=Double.parseDouble(array[0]);
type=array[1];
value =value*2.2046;
String s = String.format("%.4f", value);
value = Double.parseDouble(s);
System.out.print(value+" kg\n");
6
Try "%0.4f". That means 'format a floating point value, pad it with zeros until you have 4 digits'.user268396
i used "%.4f", but it shows this error: Exception in thread "main" java.util.MissingFormatWidthException: 0.4fMehrdad Salimi
See also stackoverflow.com/questions/10959424/… but this is not a duplicate of that because of the formatting wanted for 0.Raedwald

6 Answers

22
votes

DecimalFormat will allow you to define how many digits you want to display. A '0' will force an output of digits even if the value is zero, whereas a '#' will omit zeros.

System.out.print(new DecimalFormat("#0.0000").format(value)+" kg\n"); should to the trick.

See the documentation

Note: if used frequently, for performance reasons you should instantiate the formatter only once and store the reference: final DecimalFormat df = new DecimalFormat("#0.0000");. Then use df.format(value).

4
votes

add this instance of DecimalFormat to the top of your method:

DecimalFormat four = new DecimalFormat("#0.0000"); // will round and display the number to four decimal places. No more, no less.

// the four zeros after the decimal point above specify how many decimal places to be accurate to.
// the zero to the left of the decimal place above makes it so that numbers that start with "0." will display "0.____" vs just ".____" If you don't want the "0.", replace that 0 to the left of the decimal point with "#"

then, call the instance "four" and pass your double value when displaying:

double value = 0;
System.out.print(four.format(value) + " kg/n"); // displays 0.0000
2
votes

System.out.format("%.4f kg\n", 0.0d) prints '0.0000 kg'

2
votes

I suggest you to use the BigDecimal class for calculating with floating point values. You will be able to control the precision of the floating point arithmetic. But back to the topic :)

You could use the following:

static void test(String stringVal) {
    final BigDecimal value = new BigDecimal(stringVal).multiply(new BigDecimal("2.2046"));
    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(4);
    df.setMinimumFractionDigits(4);
    System.out.println(df.format(value) + " kg\n");
}

public static void main(String[] args) {
    test("0");
    test("1");
    test("3.1");
}

will give you the following output:

0,0000 kg

2,2046 kg

6,8343 kg
0
votes

String.format is just makign a String representation of the floating point value. If it doesnt provide a flag for a minimum precision, then just pad the end of the string with zeros.

0
votes

Use DecimalFormat to format your double value to fixed precision string output.

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.

Example -

System.out.print(new DecimalFormat("##.##").format(value)+" kg\n");