2017-06-19 66 views
0

我已經花了很長時間,試圖在java中轉換數字1.2846202978398e + 19,沒有任何運氣。目前我正在試圖做的(long)Double.parseDouble(hashes),但是這給了9223372036854775807,這顯然是不正確的。實際數字應該看起來像這樣12855103593745000000.轉換大科學數字爲長

使用int val = new BigDecimal(stringValue).intValue();返回-134589568,因爲它無法保存結果。切換代碼到long val = new BigDecimal(hashes).longValue();給我-5600541095311551616這也是不正確的。

我假設這是由於雙倍相比長的大小發生。

任何想法?

+0

BigDecimal的? BigInteger的? –

+0

[Java:將科學記數法轉換爲常規int]可能的重複(https://stackoverflow.com/questions/2546147/java-convert-scientific-notation-to-regular-int) –

+0

已更新的問題以反映您的意見:) – Jazerix

回答

1

你有沒有嘗試使用String.format

String result = String.format("%.0f", Double.parseDouble("1.2846202978398e+19")); 
System.out.println(result); 

輸出

12846202978398000000 

編輯

爲什麼你不BigDecimal工作d ○算術運算,例如:

String str = "1.2846202978398e+19"; 
BigDecimal d = new BigDecimal(str).multiply(BigDecimal.TEN); 
//         ^^^^^^^^------example of arithmetic operations 


System.out.println(String.format("%.0f", d)); 
System.out.println(String.format("%.0f", Double.parseDouble(str))); 

輸出

128462029783980000000 
12846202978398000000 
+0

這很有效!但是這個解決方案不允許我進行任何算術運算^^ – Jazerix

+0

@Jazerix爲什麼你不使用'BigDecimal'並且結果顯示它像我一樣? –

+0

@Jazerix檢查我的編輯 –

2

你的值超過long的最大大小。在這種情況下,您不能使用long。 嘗試

BigDecimal value = new BigDecimal("1.2846202978398e+19"); 

之後,你可以調用如果需要

value.toBigInteger() 

value.toBigIntegerExact() 

0

什麼:

System.out.println(new BigDecimal("1.2846202978398e+19").toBigInteger()); 
相關問題