0

The code below works ok and displays result (mDisplayNominalEff) to screen but I want to round the result to 3 places.
I assume that I need to parse string to double.
Any ideas on how to do this?

          String mDisplayNominalEff = ("" +  (myDiameter - (myPitch * 0.649519)));
          TextView displayNominalEff = (TextView) findViewById(R.id.nominalEffTV);
          displayNominalEff.setText(mDisplayNominalEff);

Edited by Centorpe

2
Contributors
6
Replies
21
Views
2 Years
Discussion Span
Last Post by Centorpe
0

The right time to round is when you are converting the floating point value to String - line 1 in the code you posted.Rather than using concatenation to force a default conversion, use String's format method to format (myDiameter - (myPitch * 0.649519)) to the right number of decimals

0

Thanks for reply James.
I've been playing around with it but can't see solution. Any chance of a bit more of a clue?

1

Simple example of formatting a float into a String:
String s = String.format("Pi = %7.4f", Math.PI);
formats the value of PI as 7 digits wide, 4 dec places (the % character signals a format specification), so s contains
Pi = 3.1416

Slightly more interesting example:
String s = String.format("Pi = %7.4f, e= %5.2f", Math.PI, Math.E);
gives
Pi = 3.1416, e= 2.72

You can do the same thing when printing by using printf instead of println
There's a complete description of all the formatting codes at
https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html
(plus lots of examples and tutorials on the web)

Edited by JamesCherrill

0

Thanks James

Below did it.

 double d = (myDiameter - (myPitch * 0.649519));
        String mDisplayNominalEff = String.format(" " + "%.3f", d) + " mm ";
        TextView displayNominalEff = (TextView) findViewById(R.id.nominalEffTV);
        displayNominalEff.setText(mDisplayNominalEff);
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.