I'd like to change float like this way:
10.5000 -> 10.5 10.0000 -> 10
How can I delete all zeros after the decimal point, and change it either float (if there's non-zeros) or int (if there were only zeros)?
Thanks in advance.
stripTrailingZeros() is an inbuilt method in Java that returns a BigDecimal which is numerically equal to this one but with any trailing zeros removed from the representation. So basically the function trims off the trailing zero from the BigDecimal value.
format(doubleVal); // This ensures no trailing zeroes and no separator if fraction part is 0 (there's a special method setDecimalSeparatorAlwaysShown(false) for that, but it seems to be already disabled by default).
Step 1: Get the string Step 2: Count number of trailing zeros n Step 3: Remove n characters from the beginning Step 4: return remaining string.
When representing a float data type in Java, we should append the letter f to the end of the data type; otherwise it will save as double. The default value of a float in Java is 0.0f. Float data type is used when you want to save memory and when calculations don't require more than 6 or 7 digits of precision.
Well the trick is that floats and doubles themselves don't really have trailing zeros per se; it's just the way they are printed (or initialized as literals) that might show them. Consider these examples:
Float.toString(10.5000); // => "10.5"
Float.toString(10.0000); // => "10.0"
You can use a DecimalFormat
to fix the example of "10.0":
new java.text.DecimalFormat("#").format(10.0); // => "10"
Why not try regexp?
new Float(10.25000f).toString().replaceAll("\\.?0*$", "")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With