0

What is the synonym of JS toFixed(2) method in Java Language. Only option is DecimalFormat ?

1 Answers1

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
  • 73
  • 7