Bialy
Bialy

Reputation: 975

How to use DecimalFormat to hide trailing zero in numbers "with decimals" only

I'm using DecimalFormat to remove trailing zeros from my outputs using the pattern #.# this produces outputs like

12.5 --> 12.5

12 --> 12

however I need to make it produce

12.5 --> 12.5

12 --> 12.0

How can this happen ?

Upvotes: 1

Views: 5308

Answers (3)

MTretowski
MTretowski

Reputation: 23

You can also set max and min precision by:

decimalFormat.setMaximumFractionDigits(maxPrecision);
decimalFormat.setMinimumFractionDigits(minPrecision);

Upvotes: 0

gobernador
gobernador

Reputation: 5739

The Javadoc for DecimalFormat says that the 0 symbol represents a digit, while # will remove the zero if it is leading or trailing. For example:

import java.text.DecimalFormat;

public class Main
{
  public static void main(String[] args)
  {
    DecimalFormat zeroes = new DecimalFormat("0.0");
    DecimalFormat hashes = new DecimalFormat("#.#");

    System.out.println(zeroes.format(12.0)); // 12.0
    System.out.println(zeroes.format(12.5)); // 12.5
    System.out.println(hashes.format(12.0)); // 12
    System.out.println(hashes.format(12.5)); // 12.5
  }
}

Upvotes: 7

user6547359
user6547359

Reputation: 204

You have to use #.0 to show the digit. # treat 0 as absent.

https://developer.android.com/reference/java/text/DecimalFormat.html

Upvotes: 0

Related Questions