I've a floating point number 29.887628583132877%.. and I've to restrict the values to 29.88.. how to do this in java
Asked
Active
Viewed 3,280 times
1
-
you can´t, you´d need to use another class if you´d want to have the exact number. – SomeJavaGuy Jan 13 '16 at 13:10
-
Are you sure you don't want to *format* your float, that is build a string representation with a specific precision in order to display it ? In such a case the linked QA won't help you much but you can just google "java format double". – Denys Séguret Jan 13 '16 at 13:11
-
Do you want to round the number or control how it is converted to a String? – Peter Lawrey Jan 13 '16 at 13:19
-
The question has been closed, but try this: `num -= num % precision`. Precision is the least count that you want to store. The precision can be any number, including a floating point number. In your example, precision will be `0.01`. – EvilTak Jan 13 '16 at 13:19
1 Answers
2
You can try this:
float num = 29.88344323323f;
System.out.println(String.format("%.2f", num));
And the result is:
29.88

Bahramdun Adil
- 5,907
- 7
- 35
- 68