Format float to show decimal places if is not zero java [duplicate]
Asked Answered
R

1

10

I need to to show decimal places of a float value only when it is different from zeros.

  1. 5.0 should be shown as 5.
  2. 7.3 should be shown as 7.3.
  3. 9.000003 should be shown as 9.000003.

How to format in this way using regex or DecimalFormat?

Rhetic answered 17/7, 2016 at 17:59 Comment(1)
check thisLegionnaire
T
25

To display decimals the way you desire, use the following snippet:

// This is to show symbol . instead of ,
DecimalFormatSymbols otherSymbols = new DecimalFormatSymbols(Locale.US);
// Define the maximum number of decimals (number of symbols #)
DecimalFormat df = new DecimalFormat("#.##########", otherSymbols);

// type: double
System.out.println(df.format(5.0)); // writes 5
System.out.println(df.format(7.3)); // writes 7.3
System.out.println(df.format(9.000003)); // writes 9.000003

// type: float
System.out.println(df.format(9.000003f)); // writes 9.000002861
Transpierce answered 17/7, 2016 at 18:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.