2017-02-11 4 views
0

Was ist das Synonym von JS toFixed (2) -Methode in Java-Sprache. Nur Option ist DecimalFormat?Java toFixed (2) Methode wie js

+1

Mögliche Duplikat [? Wie runde ich ein Doppel auf zwei Dezimalstellen in Java] (http://stackoverflow.com/questions/5710394/how-do-i-round-a-double-to-two-decimal-places-in-java) –

+0

Oder http://stackoverflow.com/questions/2538787/how-to-display-ein-out-of-float-daten-mit-2-dezimal-places-in-java –

+0

Yeah, ich habe zuerst eine –

Antwort

0

Es gibt keine, aber Sie können dies als Alternative tun:

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

Dies gilt nicht rund obwohl

+0

Danke für die Rückkehr, entschied ich mich für DecimalFormat. Nützlich als andere –