Page 1 of 1

Redondeo en JAVA

Posted: Fri Nov 18, 2011 9:07 pm
by Alex13
Hola quisiera saber como puedo redondear un numero a n lugares luego del punto en java. :?:
Yo utilizo Math.rint(x*cant_cifras)/cant_cifras, pero por ejemplo si redondeo 3.0000 lo lleva a 3.0

Re: Redondeo en JAVA

Posted: Sat Nov 19, 2011 2:07 am
by jelara
Hi Alex,

For this, you can use String.format, wich can be used with a format very similar to C++'s printf: you pass a format string and a number, and it returns a string containing the number's representation in the desired format.

For example, if you want 4 figures after the decimal point, you would use:

Code: Select all

float result = 3.0f;
String output = String.format("%.4f", result);
System.out.println(output);
which would effectively display "3.0000" on the console.

I invite you to lookup the Javadocs for the String.format function, specifically the format string, so you can harness the power of this function and add it to your contestant's toolkit. Here is the URL:

http://download.oracle.com/javase/6/doc ... tml#syntax

By the way, remember to post only in English: not all of our users are Spanish-speakers!

Re: Redondeo en JAVA

Posted: Sun Nov 20, 2011 8:12 pm
by Alex13
Ok thankĀ“s.

Re: Redondeo en JAVA

Posted: Sun Dec 04, 2011 4:45 pm
by ldsierra
Hi Alex13
You can also use this way

Code: Select all

System.out.printf("%.2f", 12.35642);     //output  12,36
System.out.printf("%.5f", 12.35);        //output  12,35000

Re: Redondeo en JAVA

Posted: Thu Dec 08, 2011 12:08 pm
by WIL
Otra manera de redondear pero que no pone los 0s a la derecha es:

Code: Select all

double num=8.122800;
System.out.println(Math.ring(num*100)/100);
Esto redondea 2 lugares despues de la coma!!!

Re: Redondeo en JAVA

Posted: Fri Dec 09, 2011 12:01 am
by jelara
@WIL: That is like the code posted by Alex13, but he was precisely asking for a way to obtain the zeroes on the right.
@ldsierra: Wow, thanks! I haven't noticed there was an actual printf function :)

Re: Redondeo en JAVA

Posted: Wed Jun 20, 2012 9:55 am
by axlluis
Hi , how can i do the same but in c#??

Re: Redondeo en JAVA

Posted: Tue Oct 09, 2012 1:52 pm
by jelara
axlluis wrote:Hi , how can i do the same but in c#??
Oh, in C# this is a piece of cake. The float.ToString function takes a parameter which controls the formatting... take a look at MSDN and all your doubts will be cleared.

Re: Redondeo en JAVA

Posted: Mon Dec 30, 2013 1:31 am
by smicky125
Heloo alex it is agreat information you share thanks lot all of you for the great help :)

Re: Redondeo en JAVA

Posted: Sun Jan 19, 2014 10:57 am
by jlfernandez
Hello, using the Format function is a great idea, i always have problem with that, thank...