Domanda

I have below code for DecimalFormat.

import java.util.*;
import java.lang.*;
import java.text.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        double d = 50.12345;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.println(df.format(d));

        d = 50.0;
        df = new DecimalFormat("#.##");
        System.out.println(df.format(d));

        d = (double) (1*1.000/Integer.parseInt(2+"")/1.000*100);
        df = new DecimalFormat("#.##");
        System.out.print(df.format(d));

        }
}

This gives me output as below.

50.12
50
50

The problem I am facing is in second number. I wanted to print it as 50.00.

Any idea how can I do the same?

Demo

È stato utile?

Soluzione

Use 0.00 as the format. # means an optional digit.

You can find all the formatting codes and their meanings here: http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html

Altri suggerimenti

use this

    double d = 50.12345;
    DecimalFormat df = new DecimalFormat("0.00");
    System.out.println(df.format(d));
    d = 50.0;
    System.out.print(df.format(d));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top