-1

Suppose, I have a double value.

double dble = 5.91742691

Now can I get that value with two digits after the point. I mean to say,can I get 5.91 from there programmatically?

One more, suppose, I want to get an integer from a double value if the double value is X.9XXXXX. Here I mean to say, I want to compare the AFTER-POINT value. For your understanding here dble's AFTER-POINT value is 91742691. How can I do that?

OneCricketeer
  • 126,858
  • 14
  • 92
  • 185
Muhammad Jobayer
  • 137
  • 1
  • 10

2 Answers2

-1

If you want to truncate a double to 2 decimal places, do

double twoDecDbl = (int)(dble * 100) / 100.0; // 5.91

or

double twoDecDbl = Math.floor(dble * 100) / 100; // 5.91

However, if you want to get the numbers after the decimal place as an integer (which I don't know why you would want to do this), then do

long decimals = Long.parseLong(("" + dble).split("\\.")[1]); // 91742691

Note: The maximum value of an int is 2,147,483,647 (10 digits there), but a double can hold 16 digits after the decimal point, so a long must be used in order to stay safe (can have 19 digits). Alternatively, you can just keep it as a String by removing the wrapping parse.

4castle
  • 28,713
  • 8
  • 60
  • 94
-1

For #1 Try it

NumberFormat formatter = new DecimalFormat("#0.00");
String s = formatter.format(dble);
double num = Double.valueOf(s);

or

dble = Math.floor(dble * 100) / 100;

For #2 Try it

double num = dble - (int)dble;

In case Integer.MIN_VALUE < dble < Integer.MAX_VALUE

Pi Vincii
  • 531
  • 4
  • 11