Android Cómo formular dígitos decimales a dos
-
21-12-2019 - |
Pregunta
Tengo a este número 0.6044610142707825 y quiero formatear esto en 600. Probé lo siguiente
new DecimalFormat("###.#")
.format(temp)
Esto devolvió 0.6. Por favor, ayúdame a encontrar el formato correcto para hacer esto.
Solución
Pruebe decimalformat
// Fetch only the first rounded off digit after decimal.
String abc = new DecimalFormat("0.#").format(0.604461014);
// Converting to integer and multiply 1000
int myFinalNo = (int) ( Double.parseDouble(abc) * 1000);
// Returns output 600
Nota:
String abc = new DecimalFormat("0.#").format(0.674461014);
int myFinalNo = (int) ( Double.parseDouble(abc) * 1000);
// Returns output 700
Si usted no desea redondear , luego use:
DecimalFormat df = new DecimalFormat("0.#");
df.setRoundingMode(RoundingMode.DOWN);
String abc = df.format(0.684461014);
int myFinalNo = (int) ( Double.parseDouble(abc) * 1000);
System.out.println ("abc="+abc + "** myFinalNo="+myFinalNo);
Otros consejos
Esto podría resolver su problema ...
temp = 0.6044610142707825;
new DecimalFormat("###")
.format(temp*1000); //converts to 604.4610142707825 and then to 604;
puedes usar
String.format("%.2f", d)
, su decimal se redondeará automáticamente.por 2 dígitos después del operador de puntos
donde d es su valor
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow