1

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()?

stella
  • 2,546
  • 2
  • 18
  • 33
  • Use methods from here: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html – Tom May 28 '16 at 09:50
  • 1
    No, the number of decimal digits is not a property of the `Float` but of its string representation. – Frank Puffer May 28 '16 at 09:52
  • FYI using split with only 1 character as separator like you do, is not treated as a regular expression behind the scene such that it is very fast, like if you used indeOf – Nicolas Filotto May 28 '16 at 09:53
  • @FrankPuffer So, I want to round the float to `9.22`. How to ensure this? – stella May 28 '16 at 09:54
  • "Precision" is the number of significant digits, not the number of digit after the decimal point. E.g. `Float.parseFloat("92223.33999444555666")` is the number `92223.34`. Also, use `float f = Float.parseFloat(...)`, not `Float f = Float.valueOf(...)`. – Andreas May 28 '16 at 09:56
  • @stella with DecimalFormat format = new DecimalFormat("#.00"); then System.out.println(format.format(f)) – Nicolas Filotto May 28 '16 at 09:59
  • @Andreas Why that? What's wrong with `valueOf`? – stella May 28 '16 at 09:59
  • 1
    It creates a boxed `Float` object instead of a primitive `float` value. – Andreas May 28 '16 at 10:00
  • Floats don't have decimal places. They have binary places, and the two are not commensurable. Your question doesn't make sense. – user207421 May 28 '16 at 10:49

1 Answers1

3

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.

Community
  • 1
  • 1
Tejash Desai
  • 466
  • 4
  • 11