当前位置: 动力学知识库 > 问答 > 编程问答 >

math - How to change 0.xxxx to xxxx in Java

问题描述:

As mentioned above. I give one example, let's say all the test values are less than 1 but greater than 0.

  • 0.12 (precision: 3, scale:2)
  • 0.345 (precision: 4, scale:3)
  • 0.6789 (precision: 5, scale:4)

how do i convert those value without hard-coding the scale and precision value.

  • 0.12 -> 12
  • 0.345 -> 345
  • 0.6789 -> 6789

for 0.1 and 0.01 and 0.001 should get 1 (i know this i bad idea but i have been given sets of business rules of the software)

i prefer solution in java but if there is a math algorithm it is better.

thanks.

网友答案:

The solution is much simpler then anybody presented here. You should use BigDecimal:

BigDecimal a = new BigDecimal("0.0000012");
BigDecimal b = a.movePointRight(a.scale());
网友答案:

Multiply by 10 until trunc x = x.

Something like (untested code):

double val = ... ; // set the value.

while(Math.floor(val) != val)
    val *= 10.0;
网友答案:

One option would be to simply convert to string, split on the decimal point, and grab the portion after it back into an integer:

Integer.parseInt((Double.toString(input_val).split('\\.'))[1])

(Note: you may want to do some error checking as part of the process; the above example code is a condensed version just designed to convey the point.)

网友答案:

Improving Amber's idea:

//for 0 <= x < 1
Integer.parseInt((Double.toString(x).replaceFirst("0.", ""));

It works well from any value below 1. Any value 1 and above will trigger java.lang.NumberFormatException

Edit: Can someone tell me the difference if the data is like below?

0.0012 -> 12
0.12   -> 12
网友答案:

Are you trying something like this?

public static void main(String[] args) {
    double d = 0.1234;
    while(d>(long)d){
        d*=10;
    }
    System.out.println((long)d);
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: