解析双数和数百万

时间:2016-12-23 12:09:42

标签: java double number-formatting

我有一个文件,表示像这个29.879.999的数百万,以及像28.09这样的双数。我正在尝试使用NumberFormat解析它们并将它们全部(整数和双精度)转换为double。这是我写的:

for (String[] entry : data) {
NumberFormat nf = NumberFormat.getInstance();
Number value = nf.parse(entry[4]).doubleValue();
System.out.println("closingvalue: "+value);
}

结果是:

closingvalue  2925.0
closingvalue  2.9879999E7
closingvalue  2809.0
closingvalue  2.7219999E7
closingvalue  2.5969999E7
closingvalue  2491.0
closingvalue  2635.0
closingvalue  2591.0

输入文件如下:

Date;Open;High;Low;Close;Log Return
2/1/2009;31.190.001;31.639.999;30.469.999;31.35;-
5/1/2009;30.73;30.77;29.08;29.25;-0.0693
6/1/2009;29.790.001;30.42;29.51;29.879.999;0.0213
7/1/2009;29.15;29.40;28.00;28.09;-0.0618
8/1/2009;27.90;27.950.001;26.860.001;27.219.999;-0.0315

我想将它们全部解析为double,就像28.09甚至数百万。感谢任何帮助。谢谢!

3 个答案:

答案 0 :(得分:1)

假设以下是有效格式

contains decimals
0.<any number> 
-0.<any number>
1.234.567.89 (last third digit is ".")

all others are integers. 

然后你所要做的就是将3个十进制条件改为&#34;,&#34;。这会将您的号码更改为

0,<any number>
-0,<any number>
1.234.567,89 (last third digit is now ",") 

并使用Locale.GERMANY进行解析

NumberFormat nf = NumberFormat.getInstance(Locale.GERMANY);
Double parsedNumber = nf.parse(value[4]).doubleValue();

编辑:这就是我要转换小数的方法。

String testString = value[4];
if(testString.size() >= 3){  //must be at least 3 digits
    int last3rdPosition = testString.size() - 3; 

    if(testString.charAt(last3rdPosition) == '.'){

         //check if the last third char is "."
         //handle cases like 31.35 (change it to 31,35)
         testString.setChar(last3rdPosition, ',');
    } else if (testString.charAt(0) == '0' 
               && testString.charAt(1) == '.'){

         //handle cases like 0.0213 (change it to 0,0213)
         testString.setChar(1, ',')
    }else if (testString.charAt(0) == '-' 
               && testString.charAt(1) == '0'
               && testString.charAt(2) == '.'){

         //handle cases like -0.0315 (change it to -0,0315)
         testString.setChar(2, ',')
    } 

}  
// do converting as per normal using Locale.GERMANY
// Locale.GERMANY will treat "." as the thousands separator
//                       and "," as the decimal separator
NumberFormat nf = NumberFormat.getInstance(Locale.GERMANY);
Double parsedNumber = nf.parse(testString).doubleValue(); 

答案 1 :(得分:0)

你的价值观不是双倍而是整数(数百万或数十亿),因为java不能用点来理解大数字。顺便提一下,我建议你BigIntegerBigDecimal来处理大数字。

答案 2 :(得分:0)

使用// Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.0.0' } } allprojects { repositories { jcenter() mavenCentral() maven { url 'http://haibison.bitbucket.org/maven-repos' } maven { url 'https://mvnrepository.com/artifact/com.github.amlcurran.showcaseview/library' } flatDir { dirs '../third_party_lib/aar' } } } 格式化文本,如下所示。

DecimalFormat