java format double no decimal places

java format double no decimal places

To format a double value with no decimal places in Java, you can use the DecimalFormat class of the java.text package.

Here's an example of how to use the DecimalFormat class to format a double value with no decimal places:

import java.text.DecimalFormat;

public class Main {
  public static void main(String[] args) {
    double number = 123.4567;

    // Create a DecimalFormat object with no decimal places
    DecimalFormat df = new DecimalFormat("#");

    // Format the number with no decimal places
    String formattedNumber = df.format(number);

    System.out.println(formattedNumber); // prints "123"
  }
}
Source:w‮.ww‬lautturi.com

This code creates a DecimalFormat object with a pattern that specifies no decimal places ("#"). The format() method of the DecimalFormat object is then used to format the number with no decimal places.

You can use a similar approach to format a double value with any number of decimal places, by specifying the appropriate pattern. For example, to format a double value with two decimal places, you can use the pattern "#.00".

Created Time:2017-11-03 22:21:06  Author:lautturi