I have Float
like this one:
Float f = Float.valueOf("9.222333999444555666");
System.out.println(f); //prints 9.222334
Is there a way to count the number of digits after the .
sign without using regex: f.toString().split("\\.")[1].length()
?
I have Float
like this one:
Float f = Float.valueOf("9.222333999444555666");
System.out.println(f); //prints 9.222334
Is there a way to count the number of digits after the .
sign without using regex: f.toString().split("\\.")[1].length()
?
Simply convert the value to String and get the place of the decimal point.
String s = "" + f;
int i = s.indexOf(".")
System.out.println("The number of digits after the decimal point are " + s.length()-i-1
EDIT: Read OP's comment and doubt about how to round off a float. That question is answered here: Format Float to n decimal places
For quick reference, use this: String.format("%.2f", f). What you have to understand that Java's Float and Double do not have methods and attributes for manipulating precision after the decimal point. There are several reasons for Java to do this, but all you should remember is to convert Float and Double to String, manipulate them however you want and then convert back.