gpt4 book ai didi

java - double 格式设置为不包含小数位

转载 作者:行者123 更新时间:2023-12-01 22:30:02 25 4
gpt4 key购买 nike

下面的代码是我的。我是一名相当新的程序员,正在学习我的第一堂 Java 类(class),所以请耐心等待。

import salespersonannualcomp.SalespersonCompensationAnnualCalculator;
import java.util.Scanner;

public class SalespersonAnnualSalesInput
{
public static void main( String[] args)
{
Scanner input = new Scanner( System.in );

//Instantiates a new instance of SalespersonCompensationAnnualCalculator
SalespersonCompensationAnnualCalculator myAnnualSales = new SalespersonCompensationAnnualCalculator();

//Prompt for and input total annual sales
System.out.println( "Please enter the total annual sales:" );

String yearlySalesString = input.nextLine();
//Declares yearlySalesInt as the variable that will store the results of Integer.parseInt
int yearlySalesInt = Integer.parseInt(yearlySalesString);

//Declares calcResults as the variable that will store the value created by the calcAnnualCompensation method
double calcResults = myAnnualSales.calcAnnualCompensation(yearlySalesInt);

//Displays the result of the calculations done for determining total annual compensation
System.out.println(" Total Annual compensation is $"+ calcResults);
System.out.println();
System.out.println(" Total Potential Annual Compensation Chart");

for(double potentialAnnualSales = yearlySalesInt;potentialAnnualSales<=(1.5*yearlySalesInt);potentialAnnualSales=potentialAnnualSales+5000)
{
double calcAnnualCompensation=myAnnualSales.calcAnnualCompensation(potentialAnnualSales);

System.out.printf( "%f %f%n ",potentialAnnualSales,calcAnnualCompensation);

}
}
}

结果输出如下所示。

Total Annual compensation is $60400.0

Total Potential Annual Compensation Chart
160000.000000 60400.000000
165000.000000 60725.000000
170000.000000 61050.000000
175000.000000 61375.000000
180000.000000 61700.000000
185000.000000 62025.000000
190000.000000 62350.000000
195000.000000 62675.000000
200000.000000 63000.000000
205000.000000 63325.000000
210000.000000 63650.000000
215000.000000 63975.000000
220000.000000 64300.000000
225000.000000 64625.000000
230000.000000 64950.000000
235000.000000 65275.000000
240000.000000 65600.000000

我希望它不显示小数位,并且所有行都能正确对齐。我的输出正确,但我在格式化方面遇到了困难。

最佳答案

你很接近...

如果您希望小数点后没有位,请将其对齐:

System.out.printf( "%10.0f %10.0f%n ",potentialAnnualSales,calcAnnualCompensation);

如果您想要小数点后两位:

System.out.printf( "%10.2f %10.2f%n ",potentialAnnualSales,calcAnnualCompensation);

本质上,10.2f 表示小数点左边 10 个空格(使用空格进行填充)和后面 2 个空格。同样,6.0f 表示小数点左边有 6 个空格,后面没有空格。您必须根据您的特定用例调整空格数量。

关于java - double 格式设置为不包含小数位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28005230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com