2015-10-06 47 views
0

我想让我的Java程序将数字舍入为小数点后两位。我一直在看我的课程资料,但找不到解决方案。下面的代码我如何让我的Java程序四舍五入?

import java.io.*; 

import java.util.*; 

public class prog58i 

{ 
public static void main (String[] args) 

{ 
//input 
System.out.print("the amount I wish to borrow is? "); 
Scanner a = new Scanner(System.in); 
double borrow = a.nextDouble(); 
//Shows amount of money someone wants to borrow 

System.out.print("The loan rate I can get is? "); 
Scanner b = new Scanner(System.in); 
double rate = b.nextDouble(); 
//Shows loan interest rate 

System.out.print("The number of months it will take me to pay of this loan is? "); 
Scanner c = new Scanner(System.in); 
double months = c.nextDouble(); 
//Shows months loan will be taken out 


//The Math Part 
double MP = borrow * (rate/1200) * (Math.pow((1+rate/1200), months))/ (Math.pow((1+rate/1200), months)- 1); 
double intrest = (MP * months) - borrow; 
double repaid = (MP*months); 

//Output 
System.out.print("My monthly payments will be $" +MP +"\n"); 
System.out.print("Total Interest Paid is $" +intrest +"\n"); 
System.out.print("Total Amount Paid is $" +repaid +"\n"); 
} 
} 

我更想找一个教程或只是如何做到这一点我一些建议。

+2

不可读 - 更加注重格式和变量名。这些事情对于非平凡的非学生代码很重要。现在还可以养成习惯。 – duffymo

回答

1

如果你只需要圆的输出,你可以做

System.out.printf("My monthly payments will be $%.2f%n", MP); 
System.out.printf("Total Interest Paid is $%.2f%n", intrest); 
System.out.printf("Total Amount Paid is $%.2f%n", repaid); 
+0

哦,好的,谢谢! –

+0

等待等待,在使用你的代码后,输出表示Total Amount Paid只是$ 2.f而不是实际的输出。 https://gyazo.com/beb0591a3e200d67cdea471be0705714编辑:修复它 –

+0

@AndrewWebb我留下了一个百分比,看看你能否弄清楚;)我现在已经修复它。 –