我不明白爲什麼我得到一個不兼容數據類型的錯誤,我使用float
作爲財務價值,我不想超過兩位小數!Java-使用浮點型 - 構造函數錯誤
我的印象是,你可以用float
爲此下,但是我得到退還給我一個錯誤說,
構造雜誌不能應用於給定類型。
當我剛做float
7,而不是7.99,它工作正常!
我誤解了float
是什麼,我需要用double
來代替嗎?
我只會展示我的雜誌課程和一些我的測試課程來演示。
測試類:
以下是我的測試類試圖用float
到小數點後兩位的段:
public static void main()
{
Magazine magazine1 = new Magazine("SanYonic Publishing", "Ayup Magazine", 7.99, "Yeshumenku Suni", "12/09/2011");
System.out.println();
magazine1.getEditor();
magazine1.getDate();
magazine1.getPublisher();
magazine1.getPublicationTitle();
magazine1.getPrice();
System.out.println();
…
}
Magazine
類:
/**
* Magazine Class - This class represents Magazine Objects
*/
public class Magazine extends Publication
{
private String editor;
private String date;
public Magazine(String publisherIn , String publicationTitleIn, float priceIn, String editorIn, String dateIn)
{
super (publisherIn , publicationTitleIn, priceIn);
editor = editorIn;
date = dateIn;
}
public void setPublication(String publisherIn, String publicationTitleIn, float priceIn)
{
publisherIn = publisher;
publicationTitleIn = publicationTitle;
priceIn = price;
}
public String getEditor()
{
System.out.println("The editor of this magazine is " + editor);
return (editor);
}
public String getDate()
{
System.out.println("The publication date of this magazine is " + date);
return (date);
}
public String getPublisher()
{
System.out.println("The publisher of this magazine is " + publisher);
return (publisher);
}
public String getPublicationTitle()
{
System.out.println("The publication title of this magazine is " + publicationTitle);
return (publicationTitle);
}
public float getPrice()
{
System.out.println("The price of this magazine is £" + price);
return (price);
}
}
我建議你不要使用'float'(或'double')進行財務計算。浮點數不精確,你可以得到奇怪的舍入誤差。使用整數或定點算法通常要好得多,即按照整數美分計算所有內容或使用BigDecimal類。 –
我強烈建議你使用BigDecimal而不是float/double,因爲基元類型有四捨五入的問題存儲十進制值的大型子集。 –