将字符串转换为双精度 - Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1097332/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert a String to Double - Java
提问by Rod
What is the easiest and correct way to convert a String number with commas (for example: 835,111.2) to a Double instance.
将带逗号的字符串数字(例如:835,111.2)转换为 Double 实例的最简单和正确的方法是什么。
Thanks.
谢谢。
采纳答案by Jon Skeet
Have a look at java.text.NumberFormat
. For example:
看看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()
}
}
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:
根据您使用的数量类型,您可能希望解析为 a BigDecimal
。最简单的方法可能是:
BigDecimal value = new BigDecimal(str.replace(",", ""));
or use a DecimalFormat
with setParseBigDecimal(true)
:
或使用DecimalFormat
with setParseBigDecimal(true)
:
DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US);
format.setParseBigDecimal(true);
BigDecimal number = (BigDecimal) format.parse("835,111.2");
回答by skaffman
Use java.text.DecimalFormat:
使用 java.text.DecimalFormat:
DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.
DecimalFormat 是 NumberFormat 的具体子类,用于格式化十进制数。它具有多种功能,旨在使解析和格式化任何语言环境中的数字成为可能,包括对西方、阿拉伯和印度数字的支持。它还支持不同种类的数字,包括整数 (123)、定点数 (123.4)、科学记数法 (1.23E4)、百分比 (12%) 和货币金额 ($123)。所有这些都可以本地化。
回答by paxdiablo
The easiest is not always the most correct. Here's the easiest:
最简单的并不总是最正确的。这是最简单的:
String s = "835,111.2";
// NumberFormatException possible.
Double d = Double.parseDouble(s.replaceAll(",",""));
I haven't bothered with locales since you specifically stated you wanted commas replaced so I'm assuming you've already established yourself as a locale with comma is the thousands separator and the period is the decimal separator. There are better answers here if you want correct (in terms of internationalization) behavior.
我没有打扰语言环境,因为您明确表示要替换逗号,所以我假设您已经将自己建立为语言环境,逗号是千位分隔符,句点是小数分隔符。如果您想要正确的(在国际化方面)行为,这里有更好的答案。
回答by Tim Büthe
A link can say more than thousand words
// Format for CANADA locale
Locale locale = Locale.CANADA;
String string = NumberFormat.getNumberInstance(locale).format(-1234.56); // -1,234.56
// Format for GERMAN locale
locale = Locale.GERMAN;
string = NumberFormat.getNumberInstance(locale).format(-1234.56); // -1.234,56
// Format for the default locale
string = NumberFormat.getNumberInstance().format(-1234.56);
// Parse a GERMAN number
try {
Number number = NumberFormat.getNumberInstance(locale.GERMAN).parse("-1.234,56");
if (number instanceof Long) {
// Long value
} else {
// Double value
}
} catch (ParseException e) {
}
回答by Narayan Yerrabachu
There is small method to convert german price format
public static BigDecimal getBigDecimalDe(String preis) throws ParseException {
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
Number number = nf.parse(preis);
return new BigDecimal(number.doubleValue());
}
----------------------------------------------------------------------------
German format BigDecimal Preis into decimal format
----------------------------------------------------------------------------
public static String decimalFormat(BigDecimal Preis){
String res = "0.00";
if (Preis != null){
NumberFormat nf = NumberFormat.getInstance(Locale.GERMANY);
if (nf instanceof DecimalFormat) {
((DecimalFormat) nf).applyPattern("###0.00");
}
res = nf.format(Preis);
}
return res;
}
---------------------------------------------------------------------------------------
/**
* This method converts Deutsche number format into Decimal format.
* @param Preis-String parameter.
* @return
*/
public static BigDecimal bigDecimalFormat(String Preis){
//MathContext mi = new MathContext(2);
BigDecimal bd = new BigDecimal(0.00);
if (!Util.isEmpty(Preis)){
try {
// getInstance() obtains local language format
NumberFormat nf = NumberFormat.getInstance(Locale.GERMAN);
nf.setMinimumFractionDigits(2);
nf.setMinimumIntegerDigits(1);
nf.setGroupingUsed(true);
java.lang.Number num = nf.parse(Preis);
double d = num.doubleValue();
bd = new BigDecimal(d);
} catch (ParseException e) {
e.printStackTrace();
}
}else{
bd = new BigDecimal(0.00);
}
//Rounding digits
return bd.setScale(2, RoundingMode.HALF_UP);
}