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);

Recommended Answers

All 6 Replies

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

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?

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)

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);

OK, that's great.
FYI, you can simplify it a bit like this:

String mDisplayNominalEff = String.format(" %.3f mm", d);

J

Excellent, ta

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.