public class RoundDecimal {
public static void main(String[] args) {
Double number1 = 18.4738, number2 = 32.2890, number3 = 49.8801;
Double r1 = roundDecimal(number1, 1);
Double r2 = roundDecimal(number1, 2);
Double r3 = roundDecimal(number2, 1);
Double r4 = roundDecimal(number2, 2);
Double r5 = roundDecimal(number3, 1);
Double r6 = roundDecimal(number3, 2);
System.out.println("r1 => " + r1); // r1 => 18.5
System.out.println("r2 => " + r2); // r2 => 18.47
System.out.println("r3 => " + r3); // r3 => 32.3
System.out.println("r4 => " + r4); // r4 => 32.29
System.out.println("r5 => " + r5); // r5 => 49.9
System.out.println("r6 => " + r6); // r6 => 49.88
}
private static double roundDecimal(double valorInicial, int numeroDecimales) {
double parteEntera = Math.floor(valorInicial);
valorInicial=(valorInicial-parteEntera)*Math.pow(10, numeroDecimales);
valorInicial=Math.round(valorInicial);
valorInicial=(valorInicial/Math.pow(10, numeroDecimales))+parteEntera;
return valorInicial;
}
}
Breve ejemplo de como redondear números decimales en java enviando como parámetro cuantos números decimales se desea.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.