开发者

How to do intelligent decimal cut off in Java?

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 ne开发者_如何学运维ed to keep 1-3 most significant digits and other set to zero.


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜