After a calculate I have a float value 10.5, 10.0 etc
ie some times the decimal value is .0
whats the best approach to not show .0 ie I would rather show 10.5, 10
Thanks.
After a calculate I have a float value 10.5, 10.0 etc
ie some times the decimal value is .0
whats the best approach to not show .0 ie I would rather show 10.5, 10
Thanks.
Simple but lengthy.
Convert your float to string. Split the string using "." as a delimeter. So the output of this is an array of 2 strings. That is the first element in the array is something that comes before decimal point and the second element is the array value after decimal.
According to you, if after decimal if the element is 0, then you prefer an integer, rather than a float value. So follow the below code:
float a=10.0;
String[] arr=a.toString().split(".");
if(Integer.parseInt(arr[1])==0) //Means, after decimal it is a 0 eg. 10.0
System.out.println(Integer.parseInt(arr[0]); //So printing only the first half
else
System.out.println(a); //Means after decimal there is some value. eg. 10.5
Hope this might have helped you.
Do not confuse the float's value with its representation when you output it:
For example, the float value may be 10.000001 but it you format it with two digits after the decimal, you end up with a string, in essence, "10.00".
There are multiple ways to format floats in Java:
String.valueOf(10.0)
(or the shorter form "" + 10.0
DecimalFormatter
and supply a format string like "#.##" to always keep two digits after the decimal even if the float has non-zero digits beyond the cutoff. This will return a formatted string.System.out.format()
and supply a format string like "%10.2f" to, again, keep 2 digits. Note that this outputs to the system console.I will leave it to you to look those up if you want to use them.
Now, for your question, you seem to want an indeterminate number of digits after the decimal but never that one zero.
float f = 10.0;
String a = "" + f;
if (a.endsWith(".0")) {
if (a.equals(".0)) {
a = "0";
} else {
a = a.substring(0, a.length() - 2);
}
}
Which will strip off the trailing ".0" and, if nothing is left, add the integer part "0".