値を特定の小数点以下の桁数に丸めるのは簡単です。
public static double round(double x, int n){
n = (int)Math.pow(n, 10);
return Math.round(x*n)/n;
}
しかし、数値の大きさに応じて実際に切り上げる必要がある小数点以下の桁数を想定できるアルゴリズムを作成できますか?
つまり、数値が大きい場合(のように100000000.12345
)、小数点以下の精度はそれほど必要ないので、小数点以下1桁または2桁に切り上げることができますが
、
数値が非常に小さい場合(のように)、0.00012345
必要になります。最大小数精度
このようなことをするためのアイデアは何ですか?
編集: 例:
argument returned decnum comment
123456789.9 123456789 0 //number is way too large so I don't need any decimal places
12345678.99 12345678 0 //number is still very large.
1234567.899 1234567 0 //still...
123456.7899 123456 0 //...
12345.67899 12345 0 //...
1234.567899 1234 0 //It's pretty large now. Still not small enough to get some decimals.
123.4567899 123.4 1 //Now, number is a little average, so 1 decimal place is included.
12.34567899 12.34 2 //The number is normal, so I want a normal 2 decimal places
1.234567899 1.234 3 //Now it's kinda small, so it now gives 3 decimal places
.1234567899 0.1234 4 //Smaller number, thus greater number of decimal places (4).
.0123456789 0.01234 5 //Even smaller
.0012345678 0.0012345 7 //Larger number of decimal places.
.0001234567 0.0001234567 10 //Smaller and smaller number, greater and greater number of decimals.
数がゼロに近づいたときに小数の数を増やし
、数がゼロから離れるにつれて小数を減らす
ことができる方法を探しています。