Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用printf格式化百分比_Java - Fatal编程技术网

Java 使用printf格式化百分比

Java 使用printf格式化百分比,java,Java,我需要声明另外两个变量,以使联邦和州的预扣税显示为百分比 例如,它们显示为(00.20%),我需要它们作为一个整体返回百分比,如(20.00%) 我尝试在底部声明新变量,例如: import java.util.Scanner; public class Taxes { public static void main(String[] args) { // TODO Auto-generated method stub System.out.prin

我需要声明另外两个变量,以使联邦和州的预扣税显示为百分比

例如,它们显示为(00.20%),我需要它们作为一个整体返回百分比,如(20.00%)

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

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();
    }
}
为了得到我想要的回报百分比,但它倾向于在最后将总回报加到净值中

任何帮助都将不胜感激,谢谢

试试这个

statewit = sTax * 100;
fedwit = fTax * 100;
编辑:您的问题可分为两部分:

  • 使用数字的惯例(正常或比例百分比*100)

  • 字符串的实数格式

  • 顺便说一句,你的代码很长,几乎没有什么格式

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


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

    java!==javascript:-(如果是这样,请发布一个答案并将其标记为有效答案,以便有相同问题的人可以从您的经验中受益!如果您不使用百分比,您需要在代码中的某个地方使用100(%),但我看不到它。在格式字符串和变量之间添加一个逗号:System.out.printf(“%.2f%%”,百分比);
     double percent=12.34;
     System.out.printf("%.2f%%", percent);
     // or in different convention "percent as number *100" 
     System.out.printf("%.2f%%", percent*100.0);