数据对象中许多字段的Java数字格式

数据对象中许多字段的Java数字格式,java,formatting,biginteger,bigdecimal,Java,Formatting,Biginteger,Bigdecimal,我有一个数据对象,它在我的数据对象类中包含一个meny BigDecimal对象以及字符串和其他类型的对象。对BigDecimal字段(如intrest rate)执行一些常见操作的最佳方法是什么 interest=interest.setScale(2, RoundingMode.HALF_UP); 我可以在setters/getter中执行,但可能更错误,我想确保每个变量都用相同的方法处理 我可以有一些可以从setter或setter调用的helper类。我讨厌在helper中编写任何代码

我有一个数据对象,它在我的数据对象类中包含一个meny BigDecimal对象以及字符串和其他类型的对象。对BigDecimal字段(如intrest rate)执行一些常见操作的最佳方法是什么

interest=interest.setScale(2, RoundingMode.HALF_UP);
  • 我可以在setters/getter中执行,但可能更错误,我想确保每个变量都用相同的方法处理

  • 我可以有一些可以从setter或setter调用的helper类。我讨厌在helper中编写任何代码


  • 还有什么好方法可以做到这一点吗?

    我会使用setters。如果我必须对所有的二进位字段这样做,我会考虑扩展BigDecimal并在构造函数上编码处理。

    < P>我将使用SETTER。如果我必须对所有的二进位字段这样做,我会考虑扩展BigDecimal并在构造函数上编码处理。

    为什么不在类中使用一个静态方法来根据需要来格式化双小数?< /p>
    public static BigDecimal formatAs(BigDecimal example) {
        //format here and return it
    }
    
    然后你可以这样使用它:

    BigDecimal interest = MyClass.formatAs(myInstance.getInterest());
    
    BigDecimal rate = MyClass.formatAs(myInstance.getRate());
    

    对于类中尽可能多的bigdecimal…

    为什么不在类中使用一个静态方法,根据需要格式化bigdecimal

    public static BigDecimal formatAs(BigDecimal example) {
        //format here and return it
    }
    
    然后你可以这样使用它:

    BigDecimal interest = MyClass.formatAs(myInstance.getInterest());
    
    BigDecimal rate = MyClass.formatAs(myInstance.getRate());
    

    对于您的类中有尽可能多的大小数…

    对象中的大小数、字符串和其他数据之间的关系是什么?非常感谢,它们在逻辑上是相关的,就像person是对象,名字是String,salary是大小数?我希望澄清一下。BigDecimal、String和对象中的其他数据之间的关系是什么?非常感谢,它们在逻辑上是相关的,比如person是对象,名字是String,salary是BigDecimal?我希望它能澄清。谢谢,这是helper方法,但问题是我什么时候调用它?这并不意味着在helper类中-直接在包含所有字段的任何类中。我将编辑关于如何调用的答案。谢谢,这是helper方法,但问题是我何时调用它?这不是在helper类中-直接在包含所有字段的任何类中。我将编辑如何打电话的答案。