我想截斷Java中的浮點數,直到兩個第一個非零十進制數字。例如,0.000134
至0.00013
或11.00401
至11.0040
。將浮點數截斷爲兩個第一個非零十進制數字
我能想到的唯一解決方案是去掉整數部分,然後乘以10,直到得到一個大於或等於10的數字。然後將原始浮點數截至number of multiplications
十進制數字。
但我可能不得不經常這樣做,所以我正在尋找更快的解決方案。
我的測試代碼:
public static String truncateTo2NonZero(double f) {
int integral = (int)f;
double decimal = f - integral;
int digits = 0;
while (decimal < 10) {
decimal *= 10;
digits++;
}
double ret = (int)decimal/Math.pow(10, digits);
ret += integral;
return Double.toString(ret);
}
public static void main(String args[]) {
final int TESTS = 1000000;
double[] floats = new double[TESTS];
Random random = new Random();
for (int i = 0; i < TESTS; ++i) {
int zeros = random.nextInt(6) + 3; // divide by 10^zeros
double digits = random.nextInt(100) + 100; // 3 last digits
floats[i] = digits/Math.pow(10,zeros) + random.nextInt(20) + 1;
}
long startTime = System.nanoTime();
for (int i = 0; i < TESTS; ++i)
truncateTo2NonZero(floats[i]);
long endTime = System.nanoTime();
long duration = endTime - startTime;
System.out.println(duration/1000000); // in milliseconds
}
我使用Windows 7家庭高級版64位。的java -version
輸出:
java version "1.8.0_20"
Java(TM) SE Runtime Environment (build 1.8.0_20-b26)
Java HotSpot(TM) 64-Bit Server VM (build 25.20-b23, mixed mode)
這看起來不像那些笨蛋。這裏的OP想要有一個動態的小數位數,即保留最多兩個第一個非零的十進制數字。 – Tunaki
@copeg不重複。這就像Tunaki說的。我認爲從我給出的兩個例子中可以清楚地看出。 – devil0150
「浮點」「十進制數字」這兩個短語不應出現在同一句子中。你應該使用'BigDecimal'。 –