我有几个字符串,我需要使用NumberFormat作为Double。 字符串可以有多种格式,如下所示:
"0" // case 1
"0.00003" // case 2
"5e-76" // case 3
"2E-10" // case 4
我使用以下代码来获取double值:
NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);
String val = "2e-7";
try {
Number number = numberFormat.parse(val);
System.out.println("number: " + number.doubleValue());
} catch (ParseException ex) {
System.out.println("error: " + ex);
}
除了案例3(运行上面的代码将打印“number:2.0”)
之外,这种方法很好要求:
我知道Double.valueOf(val)
在这里可以正常工作,但是我正在寻找仅使用NumberFormat的解决方案。
有可能实现这个目标吗?
答案 0 :(得分:3)
案例3失败,因为“e”是小写的。我们可以创建一个NumberFormat的子类,在解析它之前将其置于字符串上面。
SYSMAP System.map
DTC arch/arm64/boot/dts/15801_DVT/msm8996-v3-pmi8996-mtp_15801_DVT.dtb
DTC arch/arm64/boot/dts/15801_PVT/msm8996-v3-pmi8996-mtp_15801_PVT.dtb
DTC arch/arm64/boot/dts/15811_PVT/msm8996pro-pmi8996-mtp_15811_PVT.dtb
DTC arch/arm64/boot/dts/15811_PVT/msm8996pro-v1.1-pmi8994-mtp_15811_PVT.dtb
DTC arch/arm64/boot/dts/15811_PVT2/msm8996pro-pmi8996-mtp_15811_PVT2.dtb
DTC arch/arm64/boot/dts/15811_PVT2/msm8996pro-v1.1-pmi8994-mtp_15811_PVT2.dtb
DTC arch/arm64/boot/dts/15811_PVT3/msm8996pro-pmi8996-mtp_15811_PVT3.dtb
DTC arch/arm64/boot/dts/15811_PVT3/msm8996pro-v1.1-pmi8994-mtp_15811_PVT3.dtb
OBJCOPY arch/arm64/boot/Image
GZIP arch/arm64/boot/Image.gz
DTC arch/arm64/boot/dts/15811_PVT3/msm8996pro-v1.1-pmi8994-mtp_15811_PVT3.dtb
DTC arch/arm64/boot/dts/15811_PVT3/msm8996pro-pmi8996-mtp_15811_PVT3.dtb
DTC arch/arm64/boot/dts/15811_PVT/msm8996pro-v1.1-pmi8994-mtp_15811_PVT.dtb
DTC arch/arm64/boot/dts/15811_PVT/msm8996pro-pmi8996-mtp_15811_PVT.dtb
DTC arch/arm64/boot/dts/15801_PVT/msm8996-v3-pmi8996-mtp_15801_PVT.dtb
DTC arch/arm64/boot/dts/15801_DVT/msm8996-v3-pmi8996-mtp_15801_DVT.dtb
DTC arch/arm64/boot/dts/15811_PVT2/msm8996pro-pmi8996-mtp_15811_PVT2.dtb
DTC arch/arm64/boot/dts/15811_PVT2/msm8996pro-v1.1-pmi8994-mtp_15811_PVT2.dtb
CAT arch/arm64/boot/Image.gz-dtb
Building modules, stage 2.
MODPOST 1 modules
CC drivers/staging/qcacld-2.0/wlan.mod.o
LD [M] drivers/staging/qcacld-2.0/wlan.ko
public final class CaseInsensitiveNumberFormat extends NumberFormat {
private final NumberFormat mParent;
private final Locale mLocale;
public CaseInsensitiveNumberFormat(Locale locale) {
mParent = NumberFormat.getInstance(locale);
mLocale = locale;
}
@Override
public final Number parse(String s, ParsePosition pos) {
return mParent.parse(s.toUpperCase(mLocale), pos); // <------
}
@Override
public final StringBuffer format(double number, StringBuffer appendTo, FieldPosition pos) {
return mParent.format(number, appendTo, pos);
}
@Override
public final StringBuffer format(long number, StringBuffer appendTo, FieldPosition pos) {
return mParent.format(number, appendTo, pos);
}
}