0

I need a line of code that I can use to get the digits after the decimal place when I execute the code below:

double results = 1500 / 1000;


        txtview.setText("K " + resultsoldk);

I need the results to include the reminder as well.

rds
  • 26,253
  • 19
  • 107
  • 134
  • 1
    what is resultsoldk ? you are getting devision result in results but in textView you are using resultsoldk ? – ρяσѕρєя K Dec 04 '12 at 10:52
  • possible duplicate of [Format Float to n decimal places](http://stackoverflow.com/questions/5195837/format-float-to-n-decimal-places) – Mario S Dec 04 '12 at 17:04

4 Answers4

2

The problem is that the result of

 double results = 1500 / 1000;

is 1.0, not 1.5, because you are doing integer division. Make sure at least one of the numbers is a floating-point number when you do the division. For example:

// By adding .0 you make it a double literal instead of an int literal
double results = 1500.0 / 1000;
Jesper
  • 202,709
  • 46
  • 318
  • 350
1

You can cast using double like below

  double results = (double)1500 / 1000;

Also you can format the result using DecimalFormat

DecimalFormat df = new DecimalFormat("0.00##");
String formattedResult=df.format(results);
Rasel
  • 15,499
  • 6
  • 40
  • 50
1

You can use the String.format(...) method to format the String like this:

txtview.setText(String.format("K %f", resultsoldk));

However, this will not work in you case. As you are dividing two integers, the result will be an integer (which has no remainder). Afterwards it is converted to a double (because you assign it to a double) but at this point, the precision is already lost. You must at least convert one of the integers to a double before you divide them:

double results = (double)1500 / 1000;

or, if you use constants

double results = 1500.0 / 1000;

or

double results = 1500 / 1000.0;

or even

double results = 1500.0 / 1000.0;
Martin Thurau
  • 7,564
  • 7
  • 43
  • 80
  • 1
    This is not how you use String.format. The correct way is `String.format("K %f", resultsoldk)` I know it's silly, but that's how they designed this method at Sun. – Natix Dec 04 '12 at 11:55
  • You are absolutely right. I program a lot in Python to I'm sometimes a little confused ;) – Martin Thurau Dec 08 '12 at 17:53
0
String strResult = Double.toString(d);
strResult = strResult.replaceAll("\\d?\\.", "");

Don't know if I get it, but if what you want is the digits after the dot, then you can use this regex.

Matheus
  • 281
  • 2
  • 5