Java toFixed(2)方法这样的js

时间:2017-02-11 18:02:07

标签: java calculation tofixed

Java语言中JS toFixed(2)方法的同义词是什么? 只有选项是DecimalFormat?

1 个答案:

答案 0 :(得分:0)

没有,但你可以这样做:

/**
* 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;
}

虽然这不是圆的