What is the synonym of JS toFixed(2) method in Java Language. Only option is DecimalFormat ?
Asked
Active
Viewed 1,531 times
0
-
1Possible duplicate of [How do I round a double to two decimal places in Java?](http://stackoverflow.com/questions/5710394/how-do-i-round-a-double-to-two-decimal-places-in-java) – OneCricketeer Feb 11 '17 at 18:03
-
Or http://stackoverflow.com/questions/2538787/how-to-display-an-output-of-float-data-with-2-decimal-places-in-java – OneCricketeer Feb 11 '17 at 18:04
-
Yeah, i used first one – Hüseyin Ilgün Feb 17 '17 at 13:10
1 Answers
0
There is none but you can do this as an alternative:
/**
* Shortens a float to a specified length
* @param num The float to shorten
* @param to The length
* @return the shortened version
**/
public static String toFixed(float num, int to){
//Split at the decimal point
String[] s = String.valueOf(num).split("[.]");
//Combine the two so and shorten the second
String ending = s[1].substring(0, ((s[1].length() > to) ? to : s[1].length()));
return s[0] + '.' + ending;
}
This doesn't round though

Jeremiah
- 99
- 1
- 9
-
Thanks for return, i decided to use DecimalFormat. Useful than others – Hüseyin Ilgün Feb 13 '17 at 06:58