0

The thing is I need to print numbers like "0.019999979000" as "0.02".

The problem using String.format() is that numbers are either printed like "0.019999979" (%s) or like "0.020000000" (%f).

Is there a way to combine those effects without String manipulations?

UPD: the numbers do not always contain 2 digits after the point - that's just an example to show that the values are very close to the rounded

Alex
  • 1,165
  • 2
  • 9
  • 27
  • 2
    Use %.2f to limit it? Not sure if that is what you want to achieve... – kevcodez Jul 07 '15 at 11:39
  • Yep, that's not it. I have numbers of different length – Alex Jul 07 '15 at 11:43
  • possible duplicate of [Remove trailing zero in Java](http://stackoverflow.com/questions/14984664/remove-trailing-zero-in-java) – kevcodez Jul 07 '15 at 11:44
  • Do you want to show only one non-zero digit or something else? if your number is `0.000279` .... you want to show `0.0003` or `0.00028` ? – Karthik Jul 07 '15 at 11:45
  • @kevcodez, it's not. The author of the topic you suggested does not require rounding – Alex Jul 07 '15 at 11:47
  • @karthik, the numbers are calculated like {1,2,5}*10^(-n)*m and so, they are actually like 0,00015, for example. But because computations are binary, the calculated result is 0,00014999... - very close to the desired. So, it should be rounded really slightly, as format("%f", ...) successfully does. But it keeps the zeroes in trail – Alex Jul 07 '15 at 11:56
  • What is the range of `n` and `m`? What I am trying to understand is : "Is your value to be rounded is always less than 1?" – Karthik Jul 07 '15 at 11:59
  • Does that matter? Well, let's assume, it is. – Alex Jul 07 '15 at 12:03
  • @Alex check my answer, let me know If you wanted something else. – Karthik Jul 07 '15 at 12:06

1 Answers1

0

You seem to be looking for a number format based on the number of significant digits. Say, for n = 2, you want to display the number rounded to its first three significant digits, i.e.

1234     -> 1200
0.001234 -> 0.0012
1.999    -> 2.0
0.019999979000 -> 0.02

In that case, unfortunately, the official Java libraries won't help you (a glaring omission IMO). Under Android at least, you can use

new DecimalFormat("@@@")

for 3 significant digits; otherwise, you need to look for some available implementations. The only one I know of is the ICU4J (International Components for Unicode), but I have not evaluated it.

Franz D.
  • 1,061
  • 10
  • 23