Java-使用 float -构造函数错误

标签 java floating-point floating-accuracy financial incompatibility

我不明白为什么我会收到数据类型不兼容的错误,我正在使用 float 作为财务值,我不想超过两位小数!

我的印象是你可以用 float 来做到这一点,但是我收到一个错误返回给我说,

Constructor Magazine cannot be applied to given types.

当我将 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 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);
    }
}

最佳答案

你需要

Magazine magazine1 = new Magazine ("SanYonic Publishing", "Ayup Magazine", 7.99f, "Yeshumenku Suni", "12/09/2011");

请注意 7.99f 以修复编译问题。

请注意, float 和 double 都不适合货币计算(如果您关心准确性),因为它们只能表示一组离散的值。所有货币计算都应使用 BigDecimal 完成。

关于Java-使用 float -构造函数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8917791/

相关文章:

F# - 如何比较 float

java - Double.POSITIVE_INFINITY == Float.POSITIVE_INFINITY

c++ - 比较 float 和 int

java - 向 jframe 添加更多容器

java - 从另一个类调用对象数组列表并迭代它

java - Apache Commons 成像 (EXIF) : Setting tags/tags missing

math - float 学有问题吗?

java - volatile 关键字有什么用?

Java floatToRawIntBits/intBitsToFloat 或 doubleToRawLongBits/longBitsToDouble 等同于 ruby​​?

c++ - 为什么将 double 类型转换为 int 似乎会在第 16 位数字后四舍五入?