-1

I have the number "159.82" and I need to get it to print just "82" What I have been trying is something along the lines of

double total = 159.82;
System.out.println(total - (int) total); 

But that leaves me with 0.8199999999999 so clearly I am doing something wrong.

azro
  • 53,056
  • 7
  • 34
  • 70
Kara
  • 1

5 Answers5

0

Simple way: Turn it into an String, use indexOf to find the ".", use substring to print 82.

JensS
  • 1,151
  • 2
  • 13
  • 20
0

Would this fit what you're looking for? It outputs the decimal value, rounded to two places, as a String.

double total = 159.82;
String decimalValue = String.format("%.2f", total).split("\\.")[1];
System.out.println(decimalValue);

(Prints "82")

davidmerrick
  • 1,027
  • 1
  • 10
  • 17
0

Another solution with replaceAll, so you can replace everything until the dot :

double total = 159.82;
System.out.println(String.valueOf(total).replaceAll("^.*\\.", ""));// output = 82

This can work either with negative numbers for example :

double total = -159.82; // output = 82

Another solution if you want to get only 2 numbers then you can use :

double total = 159.82; // positive or negative
int result = Math.abs((int) (total * 100) % 100);
System.out.println(result); // output = 82
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

Due to how float/double works, the easiest solution could be to work with strings. This will return the decimals of any double input.

double input = 159.82;

String decimals = Double.toString(input);
decimals = decimals.substring(decimals.lastIndexOf('.') + 1);

System.out.println(decimals);
// prints "82"
Jonathan
  • 772
  • 4
  • 11
0
final int fraction = Integer.valueOf((total+"").replaceFirst("-?\\d+\\.", ""));    
System.out.println( fraction );
alirabiee
  • 1,286
  • 7
  • 14