2013-08-30 37 views
0

經過大量的搞亂我想出了以下代碼將任何數字的子類轉換成BigDecimal。任何數字類型BigDecimal

但我不確定這段代碼是否完全正確。我當然不滿意它的詳細程度!

有沒有更好的方法來做到這一點,並且這種方法有什麼缺陷需要我注意(除了我已經知道的浮點不精確表示問題之外)?

public DecimalSpec setValue (Number value) { 
    if (value instanceof Double) { 
     if ((((Double) value).isNaN()) 
     || (((Double) value).isInfinite())) { 
      throw new IllegalArgumentException ("Infinite or NaN values not allowed"); 
     } 
    } 
    this.value = new BigDecimal (value.toString()); 
    return this; 
} 
+2

有真的不這樣做的任何普通的方式 - 'Number'根本不打算以您使用它的方式使用 - 但您可能儘可能接近實際。 –

+3

什麼,沒有'浮動'? – Gabe

回答

2

我不知道有什麼辦法可以用較少的代碼來編寫代碼,因爲在某些方法中可以使代碼的一部分快捷。但是,我可能會將方法重載爲Double,或者讓BigDecimal代替NumberFormatException

BigDecimal做的工作:

/** May throw NumberFormatException or NullPointerException. */ 
public DecimalSpec setValue (Number value) { 
    this.value = new BigDecimal (value.toString()); 
    return this; 
} 

爲超載Double

/** May throw NullPointerException. */ 
public DecimalSpec setValue (Number value) { 
    this.value = new BigDecimal (value.toString()); 
    return this; 
} 

/** May throw NullPointerException or IllegalArgumentException. */ 
public DecimalSpec setValue (Double value) { 
    if (value.isNaN() || value.isInfinite()) { 
     throw new IllegalArgumentException ("Infinite or NaN values not allowed"); 
    } 
    return this.setValue ((Number) value); 
} 
+0

謝謝。我一直忘記Java有方法重載,我太習慣於不支持它的語言。 – GordonM

1

我認爲你有一個設計問題。使setValueBigDecimal開頭。然後,將其他類型轉換爲BigDecimal的代碼可以在代碼中的其他位置。您可以自由地將各種類型的BigDecimal轉換過載,並且可以根據輸入類型轉換爲BigDecimal

例如,

public class BigDecimalConverter { 
    public static toBigDecimal(int i) { ... } 
    public static toBigDecimal(double i) { ... } 
    ... 
} 

然後

public DecimalSpec setValue (BigDecimal value) { 
    this.value = value; 
    return this; 
} 

decimalSpec.setValue(BigDecimalConverter.toBigDecimal(myNumber)); 

不完美,當然,但那是一般的想法。一段代碼不應該做太多工作。如果有必要在某個時候接受未知類型的轉換,則可以考慮使用轉換器interface,然後使用工廠類(可能不是正確的模式名稱)來給出正確的類型。