将带逗号的字符串数字(例如:835,111.2)转换为 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()
}
}
根据您使用的数量类型,您可能希望改为解析为 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");
这篇关于将字符串转换为双精度 - Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!