Java: double format with decimal places

In Objective-C, I used this code to format a value so that a value with zero decimal places will be written without decimal places, and a value with decimal places will be written with one decimal place:

CGFloat value = 1.5; return [NSString stringWithFormat:@"%.*f",(value != floor(value)),value]; //If value == 1.5 the output will be 1.5 //If value == 1.0 the output will be 1 

I need to do the same for a double value in Java, I tried the following, but this does not work:

 return String.format("%.*f",(value != Math.floor(value)),value); 
+1
source share
3 answers

See how to print Double without commas . This will definitely give you some idea.

Exactly it will do

 DecimalFormat.getInstance().format(1.5) DecimalFormat.getInstance().format(1.0) 
+1
source

Do you mean something like?

 return value == (long) value ? ""+(long) value : ""+value; 
0
source

Not sure how to do this using the String.format ("..") method, but you can achieve the same using java.text.DecimalFormat; See an example of this code:

 import java.text.NumberFormat; import java.text.DecimalFormat; class Test { public static void main(String... args) { NumberFormat formatter = new DecimalFormat(); System.out.println(formatter.format(1.5)); System.out.println(formatter.format(1.0)); } } 

The output is 1.5 and 1, respectively.

0
source

Source: https://habr.com/ru/post/1388063/


All Articles