Format double pour au moins un chiffre significatif en Java / Android
-
09-10-2019 - |
Question
J'ai un objet Decimal que je me sers pour formater tous mes doubles valeurs à un nombre série de chiffres (disons 2) quand je les afficher. Je voudrais au format normalement à 2 décimales, mais je veux toujours au moins un chiffre significatif. Par exemple, si ma valeur est de 0,2 alors mes broches de formatter sur 0,20 et qui est grand. Cependant, si ma valeur est 0,000034 mon formatter va cracher 0.00 et je préférerais ma salive formatter sur 0,00003.
Le numéro formatteurs en Objective-C font très simplement, je peux définir un nombre maximum de chiffres que je veux montrer à 2 et le nombre minimum de chiffres significatifs à 1 et produit ma sortie désirée, mais comment puis-je le faire en Java?
J'apprécie toute aide quelqu'un peut me proposer.
Kyle
Edit:. Je suis intéressé à arrondir les valeurs ainsi 0.000037 affiche comme 0,00004
La solution
Il est pas efficace, donc si vous effectuez cette opération souvent je vais essayer une autre solution, mais si vous appelez seulement de temps en temps cette méthode fonctionne.
import java.text.DecimalFormat;
public class Rounder {
public static void main(String[] args) {
double value = 0.0000037d;
// size to the maximum number of digits you'd like to show
// used to avoid representing the number using scientific notation
// when converting to string
DecimalFormat maxDigitsFormatter = new DecimalFormat("#.###################");
StringBuilder pattern = new StringBuilder().append("0.00");
if(value < 0.01d){
String s = maxDigitsFormatter.format(value);
int i = s.indexOf(".") + 3;
while(i < s.length()-1){
pattern.append("0");
i++;
}
}
DecimalFormat df = new DecimalFormat(pattern.toString());
System.out.println("value = " + value);
System.out.println("formatted value = " + maxDigitsFormatter.format(value));
System.out.println("pattern = " + pattern);
System.out.println("rounded = " + df.format(value));
}
}
Autres conseils
import java.math.BigDecimal;
import java.math.MathContext;
public class Test {
public static void main(String[] args) {
String input = 0.000034+"";
//String input = 0.20+"";
int max = 2;
int min =1;
System.out.println(getRes(input,max,min));
}
private static String getRes(String input,int max,int min) {
double x = Double.parseDouble(((new BigDecimal(input)).unscaledValue().intValue()+"").substring(0,min));
int n = (new BigDecimal(input)).scale();
String res = new BigDecimal(x/Math.pow(10,n)).round(MathContext.DECIMAL64).setScale(n).toString();
if(n<max){
for(int i=0;i<max;i++){
res+="0";
}
}
return res;
}
}