Java: Rounding Numbers (Math.round(), DecimalFormat & printf)

  Рет қаралды 143,968

TanUv90

TanUv90

11 жыл бұрын

GitHub repo with examples github.com/SleekPanther/java-...
Java enables you to do almost anything, especially tasks involving numbers. But sometimes complicated calculations give you an answer with way too many decimals.
Most practical applications only require a few decimals. Here are 3 ways to round number in Java:
1) Using Math.round()
Java's Math class is inherently included in every program you create so there is not need for an import statement. The round() method takes a number as an argument and rounds that number to the nearest integer. On it's own this isn't spectacularly helpful but you can combine it with an easy little trick.
Inside the parentheses of the round method, multiply your number by a power of 10. Then outside the parentheses, divide by the same power of 10. The number of zeros after the '1' is the number of decimals you will have. For example: rounding to two decimals looks like this: Math.round( number * 100)/100.0; ONE OF THE NUMBERS MUST HAVE .0 AFTER IT OR JAVA WILL PERFORM INTEGER DIVISION!
2) Using System.out.printf()
The printf method is similar to print, but allows you to format the variables. The 'f' in 'printf' stands for format. To print a variable rounded to 2 decimal places the code is System.out.printf( "%.2f", number); The % symbol tells java that what comes next is a formatted variable. The The %f is replaced with the 'number' variables and the '.2' tells Java to display 2 decimals. Change the number after the period to the number of decimals you want.
NOTE: The printf method doesn't change the actual contents of the variable. After using printf, the variable still has all the decimals.
3) Using DecimalFormat
The DecimalFormat class must be imported by the statement: import java.text.DecimalFormat;
Then create a reference variable to a DecimalFormat object: DecimalFormat dFormatter and set it equal to: new DecimalFormat(); In the parentheses, place "0.00" or "#.##" to round to 2 decimals. Add more zeros of ##'s after the period to change the number of decimals.
To round the variable, type: dFormatter.format(number) This uses the format() method of the DecimalFormat class to display the number the way you specified.
DecimalFormat formats variables as strings, so if you want to use a number for calculation you have to parse it back to double or float.
Download TextPad, you can use it for free www.textpad.com/download/index...

Пікірлер: 71
@TheDelaneyCurry
@TheDelaneyCurry 3 жыл бұрын
What took me 30 minutes of fumbling through the internet, took you 4 minutes to explain. Thank you!
@phuonghuynh554
@phuonghuynh554 7 жыл бұрын
Thank you!!! Remember for the formatting, it is important to have "%.2f", number. The comma is very important, do not put +
@mladboy
@mladboy 5 жыл бұрын
Wow, finally someone explains this in a succinct, but also very clear way! Thank you!
@christiand221
@christiand221 7 жыл бұрын
This video was very helpful. I was looking for so long for this... so simple yet so hard to find. :)
@skrublaub4510
@skrublaub4510 4 жыл бұрын
The rounding part saved me. Thank you!
@christiansgroceryvlogs7769
@christiansgroceryvlogs7769 7 жыл бұрын
This is the most helpful thing I've ever seen. Quick, concise and I love your voice (it makes it more enjoyable).
@clea7403
@clea7403 3 жыл бұрын
best video about these methods, I wish I would've found this much sooner. Thank you!!
@j8acob1
@j8acob1 6 жыл бұрын
I found the documentation for this function confusing. Now I understand. Thank you!
@finngrant5385
@finngrant5385 7 жыл бұрын
very helpful, thankyou. Ive been coding nearly half a year now and I stupidly forgot how to round to specified decimal places. I was midway through my program and realized I forgot one of the first things I learned
@wcsdiaries
@wcsdiaries 4 жыл бұрын
Helped me finish a project in time. Thank you sir!
@nsk8ter524
@nsk8ter524 9 жыл бұрын
Great Explanation. Thanks!
@josealbertofernandez4593
@josealbertofernandez4593 Жыл бұрын
BRO I love this. Straight to the point. I watched a 12 min video that left me with more questions than it answered. And yet you did in the first minute 🙏🙏🙏🙏
@avinath1
@avinath1 Жыл бұрын
agreed my fellow intro to comp sci student
@AmongUs-qt3uo
@AmongUs-qt3uo Жыл бұрын
Thank you so much! I love this trick!
@rvbCabooservb
@rvbCabooservb 10 жыл бұрын
Thanks man, this was the video I was looking for.
@KooKarWai
@KooKarWai 4 жыл бұрын
This was very helpful. Thank you!
@Anhjje
@Anhjje 4 жыл бұрын
Math.round( value * 1000) / 1000.0 saved my ass for an assignment. Thank you!
@angelperalta6124
@angelperalta6124 6 жыл бұрын
Thank you. It really helped me!
@ahnafkhan2589
@ahnafkhan2589 5 жыл бұрын
Really helpful.Thanks man.
@kiki34434
@kiki34434 6 жыл бұрын
thank you this really helped!
@jessegonzalez8904
@jessegonzalez8904 4 жыл бұрын
This help me so much THANK YOU !
@tingwang1688
@tingwang1688 8 жыл бұрын
really helpful! Thank you very much!
@Bandgeek601
@Bandgeek601 5 жыл бұрын
Thank you very much kind sir. I'm a beginner and this helped me out a lot. Thank you!
@nicm.669
@nicm.669 Жыл бұрын
Thank you so much really helpful!!!
@thoseguys9900
@thoseguys9900 2 жыл бұрын
thank you! really helps!
@andreslizondro01
@andreslizondro01 9 жыл бұрын
It Works. Gracias Amigo!
@sktmx3172
@sktmx3172 2 жыл бұрын
life saver for my lab due in an hour and 39 minutes!!
@eathorsecock
@eathorsecock 9 жыл бұрын
Awesome video. Thanks!
@sportoman2003
@sportoman2003 2 жыл бұрын
Another method I found: System.out.println(String.format("%.xf", d)); Where x is the # of decimal places you want and d is a double or integer you're working with.
@afifkhaja
@afifkhaja 10 жыл бұрын
Excellent video. Thanks
@nooob1e
@nooob1e 2 жыл бұрын
THANK YOU BROTHER!!
@tempest-2124
@tempest-2124 3 жыл бұрын
very comprehensive!
@Sandysan11111
@Sandysan11111 7 жыл бұрын
YOu are just a life save, thank you
@jjohn9803
@jjohn9803 6 жыл бұрын
Thanks a lot !!! It very useful to me !!!!!!
@claytonwahlstrom1348
@claytonwahlstrom1348 9 жыл бұрын
Well done!
@minus3241
@minus3241 2 жыл бұрын
Could you help me out? I need to cut my number without rounding it. And your method rounds the number. For example the number 21.4567 should be shown an 21.45 and not as 21.46 , which method could I use? Or what should I do generally?
@BennyElie
@BennyElie 4 жыл бұрын
You can also simply do casting : double number = 3.141592653; double rounded = (int) (number * 100) / 100.0; System.out.println(rounded); 3.14
@mirabellebonnet9113
@mirabellebonnet9113 3 жыл бұрын
You can also simply do casting : double number = 3.141592653; System.out.format("%.2f",number); 3.14
@23mooncakecopters
@23mooncakecopters 10 жыл бұрын
Thank you so much :)
@masrxxr
@masrxxr Жыл бұрын
Thanks brother
@ProfessorSquid
@ProfessorSquid 4 жыл бұрын
thanks
@lunatutoriales7532
@lunatutoriales7532 7 жыл бұрын
Muy bueno gracias!!!!
@sandupaegodage8163
@sandupaegodage8163 4 жыл бұрын
thank You
@matty2620
@matty2620 9 ай бұрын
thank you
@FezileNkuna
@FezileNkuna 6 жыл бұрын
Thanks.
@drgjengdahl2709
@drgjengdahl2709 6 жыл бұрын
THANK YOU!!!!
@smotteh
@smotteh 7 жыл бұрын
1:05 ...
@jad3clan657
@jad3clan657 4 жыл бұрын
alluminati confirmed?????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????
@kush5749
@kush5749 2 жыл бұрын
Who said "VARIABLE"
@BloodlyKill
@BloodlyKill 7 жыл бұрын
Thanks
@cyrusthe0ther795
@cyrusthe0ther795 Жыл бұрын
Gracias
@cutieboo233
@cutieboo233 5 жыл бұрын
Thank you hero! Could you please tell me how to make user input to be 2 decimal??
@cutieboo233
@cutieboo233 5 жыл бұрын
ohhh never mind, I figured out :p
@isaacmateosv
@isaacmateosv 4 жыл бұрын
@@cutieboo233 how? D:
@cutieboo233
@cutieboo233 4 жыл бұрын
isaacmateosv try number = input.nextDouble();
@avinath1
@avinath1 Жыл бұрын
@@cutieboo233 that doesnt do anything
@cutieboo233
@cutieboo233 Жыл бұрын
@@avinath1 Then figure out yourself don't come here to copy my code
@user-zl3wg5xo8j
@user-zl3wg5xo8j 9 ай бұрын
nice
@michiel4697
@michiel4697 2 жыл бұрын
thx
@nicholasmercer6397
@nicholasmercer6397 4 жыл бұрын
BROOOOO, tytytytyty
@jawaddoufare8614
@jawaddoufare8614 3 жыл бұрын
actually,the first method(Math.round()) doesn't gives an exact solution if the first number after the point is bigger than 5 Cause the method always go to the bigger value when the first number after the point is bigger than 5 .
@Warpgatez
@Warpgatez 3 жыл бұрын
Was that a demon saying "variable"?
@masquerade0133
@masquerade0133 5 жыл бұрын
didnt know badger from breaking bad taught java
@willhand253
@willhand253 9 жыл бұрын
or when you multiply, you could multiply by .100..... impressive right. im a freaking genius
@whereyouatgeorge1488
@whereyouatgeorge1488 Жыл бұрын
mad zesty
@feathersmcgraw4650
@feathersmcgraw4650 4 жыл бұрын
you.......are ..... god......
@simoncha8733
@simoncha8733 4 жыл бұрын
thanks
How to tutorial Java: Rounding numbers
4:41
GreatnessProgramming
Рет қаралды 41 М.
Slow motion boy #shorts by Tsuriki Show
00:14
Tsuriki Show
Рет қаралды 3,4 МЛН
How Many Balloons Does It Take To Fly?
00:18
MrBeast
Рет қаралды 155 МЛН
Who has won ?? 😀 #shortvideo #lizzyisaeva
00:24
Lizzy Isaeva
Рет қаралды 63 МЛН
Floating Point Numbers | Fixed Point Number vs Floating Point Numbers
13:40
ALL ABOUT ELECTRONICS
Рет қаралды 18 М.
DecimalFormat Class
13:15
cpfaffinator
Рет қаралды 648
Java String Format
19:52
Mike Møller Nielsen
Рет қаралды 20 М.
Java Main Method Explained - What Does All That Stuff Mean?
7:10
Coding with John
Рет қаралды 223 М.
Double In Java - Double VS Int
6:27
Alex Lee
Рет қаралды 9 М.
Fibonacci Series In Java With Recursion - Full Tutorial (FAST Algorithm)
15:11
computers suck at division (a painful discovery)
5:09
Low Level Learning
Рет қаралды 1,6 МЛН
Slow motion boy #shorts by Tsuriki Show
00:14
Tsuriki Show
Рет қаралды 3,4 МЛН