Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get first 2 decimal digits of a double

Tags:

java

math

double

I have a huge double that i want to get the first 2 decimal digits as float from. Here is an example:

double x = 0.36843871
float y = magicFunction(x)
print(y)

Output: 36

If you don't understand feel free to ask questions.

like image 769
ThatPixelCherry Avatar asked Dec 19 '15 04:12

ThatPixelCherry


2 Answers

You could multiply by 100 and use Math.floor(double) like

int y = (int) Math.floor(x * 100);
System.out.println(y);

I get (the requested)

36

Note that if you use float, then you would get 36.0.

like image 161
Elliott Frisch Avatar answered Oct 28 '22 18:10

Elliott Frisch


You could multiply x by 100 and use int instead of float. I tried the below code:

double x = 0.36843871;
int y = (int)(x*100);
System.out.println(y);

And got output as:

36
like image 37
NewBee Developer Avatar answered Oct 28 '22 19:10

NewBee Developer