2009-07-08 8 views
24

文字列の数値をカンマ(たとえば835,111.2など)でDoubleインスタンスに変換する最も簡単で正しい方法は何ですか?文字列をDouble-Javaに変換する

ありがとうございました。

答えて

46

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に解析することがあります。それを行うための最も簡単な方法は、おそらくです:

BigDecimal value = new BigDecimal(str.replace(",", "")); 

またはDecimalFormatsetParseBigDecimal(true)を使用します。

DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US); 
format.setParseBigDecimal(true); 
BigDecimal number = (BigDecimal) format.parse("835,111.2"); 
+0

あなたは 'NumberFormat.getInstance'は常に' DecimalFormat'のインスタンスを返しますよろしいです。カンマをドットで手動で置き換えても、ローカリゼーションのアイデアを打ち破ることはできませんか? –

+0

@Tadeusz:質問は、「現在のロケールの数字」ではなく、「カンマの付いた数字」に関する質問です。質問が具体的である場合、回答が具体的であることは理にかなっています。 DecimalFormatを返さない可能性のあるNumberFormat.getInstanceについては、それが可能です。私は正直言ってそれを一番良い方法ではないと思っています。 APIは特に有用ではありません:( –

+0

良い。非常に有用 –

5

使用java.text.DecimalFormatの:

てDecimalFormatは具象サブクラス のです10進数の の数値をフォーマットするNumberFormat。西洋語、アラビア語、 およびインド数字のサポートを含む および任意のロケールでの書式番号 を解析できるように設計されたさまざまな機能 があります。 の整数(123)、固定小数点数 (123.4)、科学的表記法(1.23E4)、 パーセント(12%)、および通貨 金額($ 123)を含む の数字もサポートしています。これらのすべては にローカライズすることができます。

10

最も簡単なものが常に正しいとは限りません。ここでは最も簡単です:

String s = "835,111.2"; 
// NumberFormatException possible. 
Double d = Double.parseDouble(s.replaceAll(",","")); 

あなたは、特にあなたがコンマので、私はカンマでロケールが千単位の区切りで、期間があるとして、あなたはすでに自分自身を確立してきたと仮定している置き換えたかっ述べたので、私は、ロケールで困っていません小数点記号。あなたが正しい(国際化の観点から)振る舞いを望むなら、ここでより良い答えがあります。

2

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) { 
} 
+3

死んでリンクすることはできません –

+0

良い方法は、[道のマシンを使用して](http://web.archive.org/web/20110702052222/http: //exampleedepot.com/egs/java.text/Numbers.html)、サンプルをコピーしました –

1
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); 

    } 
関連する問題