使用printf格式化百分比

时间:2016-03-22 18:55:09

标签: java

import java.util.Scanner;

public class Taxes {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        System.out.printf("Enter the employees first name: ");

        Scanner input = new Scanner(System.in);

        String fName = input.nextLine();

        System.out.printf("Enter the employees last name: ");

        String lName = input.nextLine();

        System.out.printf("Enter the hours worked for the week: ");

        double hours = input.nextDouble();

        System.out.printf("Enter the hourly pay rate: ");

        double pay = input.nextDouble();

        double gross = hours * pay;

        System.out.printf("Enter the federal tax withholding: ");

        double fed = input.nextDouble();
        double fTax = gross * fed;

        System.out.printf("Enter the state tax withholding: ");

        double state = input.nextDouble();
        double sTax = gross * state;

        double Ttax = sTax + fTax;

        double net = gross - Ttax;



        System.out.printf(
                "Employee Name:%s %s\n\nHours Worked:%s hours\n\nPay Rate:$%.2f\n\nGross pay:$%.2f\n\nDeductions: \n\n\tFederal Withholding:(%.2f%%)$%.2f \n\n"
                        + "\tState Withholding:(%.2f%%)$%.2f\n\n\tTotal Witholding:$%.2f\n\nNet Pay:$%.2f",
                fName, lName, hours, pay, gross, fed, fTax, state, sTax, Ttax, net);

        input.close();
    }
}

我需要申报另外两个变量,以便将联邦和州的预扣税显示为百分比。

示例他们显示为(00.20%)我需要他们返回整体百分比(20.00%)

我尝试在底部声明新变量,例如:

statewit = sTax * 100;
fedwit = fTax * 100;

让百分比按我的意愿返回,但它往往会在结尾处将总数加到网上。

非常感谢任何帮助,谢谢!

1 个答案:

答案 0 :(得分:1)

试试这个。

 double percent=12.34;
 System.out.printf("%.2f%%", percent);
 // or in different convention "percent as number *100" 
 System.out.printf("%.2f%%", percent*100.0);

编辑:您的问题可分为两部分:

  1. 使用数字的惯例(正常或百分比缩放* 100)

  2. 真正格式化为字符串

  3. 顺便说一下你的代码很长,几乎没有格式化。

    Java没有特殊类型的百分比值。类型:double,BigDecimal可以与他的行为一起使用,或者也可以是整数类型,如果程序员保持整数约定

    编辑:谢谢Costis Aivalis,逗号更正:)