I have an issue when using the round function in that if the last value after the decimal place is 0 it gets dropped. Is there a way to force the return of a trailing 0?The code I have is effectively:
(Float.valueOf('0.75') * (index -1) / index).round(2)
The ‘0.75’ is a string variable and I am doing the calculation in a For loop index : (2…4)
It works fine for index = 2 and 4, but for index = 3 the result I get is 0.5 but I need it to be 0.50 for a string comparison.
Can anyone give me a pointer?
Thanks
2 Likes
Hey Richard,
NumberFormat is the thing you need.
NumberFormat nf = NumberFormat.getInstance()
nf.setMinimumFractionDigits(2)
for(int index = 2; index < 5; index++) {
println nf.format((Float.valueOf('0.75') * (index -1) / index).round(2))
}
Output:
0.380.500.56
I think you might want to use the DecimalFormat Class
https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html
But since I’m not an expert on this stuff, see this article for a more complete treatise:
Thanks for the help - it is working perfectly now.
For anyone else, you need to add
import java.text.NumberFormat as NumberFormat