Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Java, how to delete all 0s in float?

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.

like image 728
clerksx Avatar asked Dec 01 '11 19:12

clerksx


People also ask

How do I get rid of trailing zeros in Java?

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.

How do you remove extra zeros from a double in Java?

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).

How do you remove trailing zeros from a string?

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.

How do you float a number in Java?

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.


2 Answers

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"
like image 62
maerics Avatar answered Oct 03 '22 05:10

maerics


Why not try regexp?

new Float(10.25000f).toString().replaceAll("\\.?0*$", "")
like image 28
Nthalk Avatar answered Oct 03 '22 06:10

Nthalk