2017-02-11 2 views
0

Quel est le synonyme de la méthode JS toFixed (2) en langage Java. Seule l'option est DecimalFormat?Méthode Java toFixed (2) telle que js

+1

double possible de [? Comment puis-je compléterai un double à deux décimales en Java] (http://stackoverflow.com/questions/5710394/how-do-i-round-a-double-to-two-decimal-places-in-java) –

+0

Ou http://stackoverflow.com/questions/2538787/comment-afficher-une-sortie-de-float-data-avec-2-decimal-places-en-java –

+0

Ouais, j'ai utilisé le premier –

Répondre

0

Il n'y a que vous pouvez faire cela comme une 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; 
} 

Ce ne arrondit que

+0

Merci pour le retour, j'ai décidé d'utiliser DecimalFormat. Utile que d'autres –