Reputation: 1352
I get the "price" value from the server in Double
and I need to put it in TextView in my application. The problem is: when price = 500 I get 500.0 because it's Double
. I want it to look like 500.55 or 500.50 or just 500 - how do I format these numbers in the right way?
Upvotes: 1
Views: 1413
Reputation: 111
Use DecimalFormat
double price = 500.0;
DecimalFormat format = new DecimalFormat("0.###");
System.out.println(format.format(price));
EDIT
Ok, than try something different:
public static String formatPrice ( double price){
if (price == (long) price)
return String.format("%d", (long) price);
else
return String.format("%s", price);
}
Upvotes: 2
Reputation: 37404
you can use rexgex
to do the formatting
1.) Create a function to identify the following conditions
If precision values contains only zeros then truncate them
If there is any non-zero value after decimal then return original value
public String formatValue(double d){
String dStr = String.valueOf(d);
String value = dStr.matches("\\d+\\.\\d*[1-9]\\d*") ? dStr : dStr.substring(0,dStr.indexOf("."));
return value;
}
\\d+\\.\\d*[1-9]\\d*
: match one or more digits then a .
\\d*[1-9]\\d*
: match one non-zero valueTest cases
yourTextView.setText(formatValue(500.00000000)); // 500
yourTextView.setText(formatValue(500.0001)); // 500.0001
yourTextView.setText(formatValue(500)); // 500
yourTextView.setText(formatValue(500.1111)); // 500.1111
Learn more about regular expressions
Upvotes: 3
Reputation: 1
You need to explicitly get the int value using method intValue() like this:
Double d = 5.25; Integer i = d.intValue();
OR double d = 5.25; int i = (int) d;
Upvotes: -1
Reputation: 323
Use the String#format method.
Read about it here: https://www.dotnetperls.com/format-java or in the JavaDoc
Upvotes: 0