【问题标题】:Formatting, Big Decimal, interest to percent please格式化,大十进制,请按百分比计算
【发布时间】:2020-06-05 02:29:30
【问题描述】:

有人可以解释一下用法,而不仅仅是回答我真的很想学习如何做到这一点。这是我使用 Java 的第二个月,请解释 Java 中的格式化用法。非常感谢。对此,我真的非常感激。随意询问有关 C++ 或 python 的任何其他问题。我在格式化、大小数使用以及如何设置方面需要帮助


import java.util.*;

import java.math.BigDecimal;

import java.text.NumberFormat;

import java.math.*;


public class Main{
    public static void main(String[] args)
    {

        Scanner myCalculation = new Scanner(System.in);

        System.out.print("Welcome to the Interest Calculator \n\n");
        String option = "y";
        while (option.equalsIgnoreCase("y"))
        {

            System.out.print("Enter Loan Amount: ");
            //double loanAmount = 520000;
            double loanAmount = myCalculation.nextDouble();
            //Get Interest rate from user
            System.out.print("Enter Interest Rate: ");
            // double interRate = .05375;
            double interRate = myCalculation.nextDouble();


            double interest = loanAmount * interRate;

            System.out.printf("%.3f", interest);
            System.out.println();


            //prompt user to continue? if he enter y then it will Continue
            //else it will stop
            //System.out.println("Continue? (y:n): ");
            Scanner scan = new Scanner(System.in);
            boolean stop = false;    
            while(!stop) {
            //do whatever
                System.out.println("Would you like to continue? (yes or no)");
                String s = scan.nextLine();
                if(s.equals("no")) {
                    stop = true;
                }
            }

        }
    }
}

【问题讨论】:

  • 我不清楚问题是什么
  • 我正在尝试使用 BigDecimal 类来计算利息金额,以确保所有计算都是准确的。然后我想用NumberFormat抽象类基类格式化利率、利息金额和贷款金额和利息。
  • 我将假设此代码不会用于真钱。如果您确实想在真钱上使用它,请使用专门为处理货币计算而构建的库。
  • NumberFormat 实际上并不是抽象的,但它 DecimalFormat (javadoc) 的基类,您可能会想要使用它,因为它可以格式化百分比。
  • 您介意分享一下如何使用 NumberFormat 函数

标签: java currency number-formatting bigdecimal


【解决方案1】:
Scanner in = new Scanner(System.in);
System.out.print("enter double");
double d = in.nextDouble(); //doubles
System.out.print("enter int");
int i = in.nextInt(); //ints

System.out.print("enter text");
String text = in.next(); //gets a string up to the first space
in.nextLine();
System.out.print("enter text w/ spaces");
String line = in.nextLine(); //gets a string up to the first space

System.out.println(d);
System.out.println(i);
System.out.println(text);
System.out.println(line);
in.close();

System.out.println(new DecimalFormat("#.###").format(4.567346344634));

【讨论】:

    猜你喜欢
    • 2022-06-11
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多