2017-11-10 3 views
-1

したがって、 "会計フォーマット"でフォーマットされた文字列として返される金額を返すメソッドを作成する必要があります。すなわち、負の量はそのまわりに括弧を持ち、小数点の左に3桁ごとにカンマが続きます。小数点以下の桁数は小数点第2位を四捨五入します。 量が負の場合、返される文字列の右端には、 の右括弧が付きます。量が正の場合、戻り文字列は の右端にスペースがあります。提供される幅によって、返される文字列の幅は何文字になるかが決まります。幅が、フォーマットされた値を表現するために必要な最小文字数より大きい場合、返される文字列はスペースで左に埋められます。幅がこの最小値以下の場合、幅は無視されます。このメソッドで埋め込まれたスペースを含む文字列をJavaで返す方法

これまでのところ、私のコードは次のとおりです。私は10の幅の入力番号「1000」、それが持つべき「1,000.00」の代わりに「1,000.00」を出力する場合、このコードで

String amountString = String.format("%,.2f", amt); 

    if (amt < 0){ 
     String positionAmount = amountString.substring(1, amountString.length()); 
     amountString = '(' + positionAmount + ")"; 
    } 
    else{ 

    } 

    //apply width 
    if(amountString.length() < width){ 
     amountString = amountString + " "; 
    } 
    return amountString; 
}}` 

私の問題がありますスペースは先頭にスペースがあります。これは、幅が10で、最後にスペースが1つだけあるためです。

これを修正するにはどうすればよいですか?ありがとう!

+0

をamountString前に "" を追加していないので、これはですstart(ammountString = "" + amountString + "") – crammeur

+0

しかし今、私はwで0を入力すると巾1 "0.00"の代わりに "0.00" –

+0

これを見てください。http://puu.sh/yjfts/2f1b2a6c5a.png –

答えて

0
String amountString = String.format("%,.2f", amt); 

    if (amt < 0){ 
     amountString = amountString.substring(1, amountString.length()); 
     amountString = "(" + amountString + ")"; 
    } 
    else if(amountString.length() < width){ 
     amountString = amountString + " "; 
    } 

    while(amountString.length() < width) 
    { 
     amountString = " " + amountString; 
    } 

    System.out.println("{" + amountString + "}"); 

あなたがにスペースを入れていないため、出力

{  1,000.00 } //amt 1000, width 15 

{ 1,000.00 } //amt 1000, width 10 

{(1,000.00)} //amt 1000, width 10 not sure about the bracket but this is my guess 

{  5.00 } //amt 5, width 10 

{      2,020.57 } //amt 2020.5678, width 30 

{0.00} //amt 0, width 1 
+0

この種の1000の幅10の問題を解決しますが、 "0.0" 0.00 "となる。ここに私のテストフレームワークのスクリーンショットがありますhttp://puu.sh/yjfts/2f1b2a6c5a.png –

+0

私はそれがそのケースを解決するはずですが、あなたの質問にはどこにも言及しません。あなたの説明によると、すべての正の数は、最も右の文字としてスペースを持つ必要があります。 –

+0

これはすべてのテストケースで動作するはずです@DeemAh –

0

あなたは

//apply right side 
if (amountString.length() < width) { 
    amountString = amountString + " "; 
} 

//apply left side 
if(amountString.length() < width){ 
    amountString = " " + amountString; 
} 
+0

これを見てくださいhttp://puu.sh/yjfts/2f1b2a6c5a.png ここで、幅1の0を入力すると、 "0.00"の代わりに "0.00" –

関連する問題