本文介紹了將字符串轉(zhuǎn)換為雙精度 - Java的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
將帶逗號的字符串數(shù)字(例如:835,111.2)轉(zhuǎn)換為 Double 實例的最簡單和正確的方法是什么.
What is the easiest and correct way to convert a String number with commas (for example: 835,111.2) to a Double instance.
謝謝.
推薦答案
看看java.text.NumberFormat
.例如:
import java.text.*;
import java.util.*;
public class Test
{
// Just for the sake of a simple test program!
public static void main(String[] args) throws Exception
{
NumberFormat format = NumberFormat.getInstance(Locale.US);
Number number = format.parse("835,111.2");
System.out.println(number); // or use number.doubleValue()
}
}
根據(jù)您使用的數(shù)量類型,您可能希望改為解析為 BigDecimal
.最簡單的方法可能是:
Depending on what kind of quantity you're using though, you might want to parse to a BigDecimal
instead. The easiest way of doing that is probably:
BigDecimal value = new BigDecimal(str.replace(",", ""));
或使用 DecimalFormat
與 setParseBigDecimal(true)
:
DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
format.setParseBigDecimal(true);
BigDecimal number = (BigDecimal) format.parse("835,111.2");
這篇關(guān)于將字符串轉(zhuǎn)換為雙精度 - Java的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!