1

I want to implement or use some library for an intelligent decimal cut off.

I mean that I would like to get: from 3.456432 -> 3.4, from 0.0000023232432 -> 0.000002 and from 0.000000000001 -> 0.0 (or something like that). I need this feature for a convinient user GUI.

Thereby I need to reduce number of digits that are not equal to zero. I need to keep 1-3 most significant digits and other set to zero.

MaXal
  • 841
  • 2
  • 8
  • 23
  • 3
    If you are rounding then 3.456432 should round to 3.46. – DwB Nov 22 '10 at 18:56
  • 6
    It seems like you need to figure out what you mean by "intelligent cut-off". Implementation should be easy after that. From your examples it sounds like you want to round to both a certain number of significant digits and a certain absolute precision? – Cascabel Nov 22 '10 at 18:57
  • What do you mean by intelligent decimal cut off? – CoolBeans Nov 22 '10 at 18:58
  • I need to reduce number of digits that are not equal to zero. I need to keep 1-3 most significant digits and other set to zero. – MaXal Nov 22 '10 at 19:21
  • I believe this is a Duplicate: http://stackoverflow.com/questions/202302/rounding-to-an-arbitrary-number-of-significant-digits – Taylor Leese Nov 22 '10 at 20:53

3 Answers3

3

Have you taken a look at the DecimalFormat API?

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.

Santa
  • 11,381
  • 8
  • 51
  • 64
2

If it is of any help, you can use the following method to round a double to a specified number of significant digits. There are however no functionality in the standard API to output the result in a reasonable manner:

private static double round(double v, int sigDigits) {
    double f = Math.pow(10, Math.ceil(Math.log10(Math.abs(v))) - sigDigits);
    return Math.round(v/f)*f;
}
jarnbjo
  • 33,923
  • 7
  • 70
  • 94
  • It works well for big numbers but for small situation is worst. For example, it rounds 0.000012 as 1.2299999999999999E-5. It's not what I want. – MaXal Nov 22 '10 at 20:16
  • Not it will be 0.000012. Because in this case we have two significant digits: 1 and 2 so we can't round them. – MaXal Nov 22 '10 at 20:46
1

Since Java 5, java.util has a Formatter class which can do what you need.

hexium
  • 733
  • 1
  • 7
  • 12