简体   繁体   English

限制返回的小数位数?

[英]Limit decimal places in a return?

I'm new and trying to stick to basic concepts here. 我是新手,并且在这里坚持基本概念。 How do I limit the decimals in an answer pulled from a return in a different class?I'm not sure how to write a.calculateTuition in a price format 000.00. 我如何限制从不同类的返回值中得出的答案中的小数位?我不确定如何以000.00的价格格式编写a.calculateTuition I couldn't find a good way to use the DecimalFormat class and Math.round() is not accurate enough for prices. 我找不到使用DecimalFormat类的好方法,而Math.round()对于价格而言不够准确。 Thanks in advance! 提前致谢!

From the class: 从班级:

public double creditHours;
public double calculateTuition(){
    double totalCost=0;
    double costPerHour=124.04;
    totalCost = creditHours * costPerHour;

    return totalCost;
}

From Main: 从主要:

Student a=new Student();
a.setHours(3);
System.out.println("Cost is " +  a.calculateTuition());

Usually it's considered to be best practise to use BigDecimal with currency / money related computations because of the precision it offers. 通常,由于BigDecimal提供的精度,因此最好将BigDecimal与货币/金钱相关的计算一起使用。

If you decide to use BigDecimal, it also has .setScale() and many other useful methods you might find useful. 如果决定使用BigDecimal,它还具有.setScale()和许多其他有用的方法,您可能会觉得有用。

You can use the following utility to round the number of decimals you want, public static double round(double value, int places) { if (places < 0) throw new IllegalArgumentException(); 您可以使用以下实用程序舍入所需的小数位数,公共静态double舍入(double值,int位){如果(位<0)抛出new IllegalArgumentException();

long factor = (long) Math.pow(10, places);
value = value * factor;
long tmp = Math.round(value);
return (double) tmp / factor;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM