It's not a secret anymore!*
The moose likes Beginning Java and the fly likes confusion in division Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "confusion in division" Watch "confusion in division" New topic
Author

confusion in division

Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

hi all;

in maths,

22/12=1.833..

i want to get the answer(1.833) in java...is ther any special function


i want to get output..but i can not ..please helpme..

thanks & regards,
seetharaman
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41599
    
  55
If you use "22/12", the JVM assumes that you want an integer result, because both numbers are integer. If you write "22.0/12" or "22/12.0" you will get a floating-point result.


Ping & DNS - my free Android networking tools app
Chiranjeevi Kanthraj
Ranch Hand

Joined: Feb 18, 2008
Posts: 289

i know this is not the good solution for your problem.
i think it will slove your problem
String a=""+22/12.0;//take in a String
System.out.println(new Float(a.substring(0,5))); //take the required value convert it to Float


-Chiru
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41599
    
  55
Originally posted by chiru surya:
...

Don't do this. For formatted printing you can use System.out.printf, and for in-memory formatting you can use the java.text.NumberFormat class. Both have plenty of options for formatting the number.
Chiranjeevi Kanthraj
Ranch Hand

Joined: Feb 18, 2008
Posts: 289

formatting the number

Thank for this
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19679
    
  18

Originally posted by chiru surya:
String a=""+22/12.0;//take in a String

Never ever ever do that again. The 22/12.0 part will be converted to a string, then added to the empty string. From now on, just call String.valueOf(22/12.0) - the resulting string will be the same but there will be fewer objects created.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

thanks ulf Dittmer
Chiranjeevi Kanthraj
Ranch Hand

Joined: Feb 18, 2008
Posts: 289

Never ever ever do that again.

Thanks man.
for this good Suggestion. Really thanks
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: confusion in division