Home Java javaTutorial Sample code sharing for monthly equal payment and interest first and cost later calculation in Java

Sample code sharing for monthly equal payment and interest first and cost later calculation in Java

Mar 29, 2017 am 10:19 AM

General credit loans provide two repayment methods: equal monthly payments or interest first and then principal. Equal monthly payment means repaying an equal part of the principal and interest every month. The principal you are using is actually decreasing month by month. Interest first and then principal means that the interest is paid first and the principal is returned at maturity. This article will introduce their implementation methods. It has a very good reference value, let’s take a look with the editor below

General credit loans will provide two repayment methods: equal monthly payments or interest first and then principal. Equal monthly payment means repaying an equal part of the principal and interest every month. The principal you are using is actually decreasing month by month. Interest first and then principal means that the interest is paid first and the principal is returned at maturity.

Equal monthly payment

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
/**
 * <p>Title: 等额本息还款工具类</p>
 *
 */
public class CPMUtils{
 /**
 * <p>Description: 每月还款总额。〔贷款本金×月利率×(1+月利率)^还款月数〕÷〔(1+月利率)^还款月数-1〕</p>
 * @param principal 贷款本金
 * @param monthlyInterestRate 月利率
 * @param amount 期数
 * @return
 */
 public static BigDecimal monthlyRepayment(BigDecimal principal, BigDecimal monthlyInterestRate, int amount){
 //(1+月利率)^还款月数
 BigDecimal temp = monthlyInterestRate.add(MoneyUtils.ONE).pow(amount);
 return principal.multiply(monthlyInterestRate)
   .multiply(temp)
   .pide(temp.subtract(MoneyUtils.ONE), MoneyUtils.MATHCONTEXT);
 }
 /**
 * <p>Description: 月还款利息。(贷款本金×月利率-月还款额)*(1+月利率)^(当前期数-1)+月还款额</p>
 * @param principal 贷款本金
 * @param monthlyInterestRate 月利率
 * @param monthlyRepayment 月还款额
 * @param number 当前期数
 * @return
 */
 public static BigDecimal monthlyInterest(BigDecimal principal, BigDecimal monthlyInterestRate, BigDecimal monthlyRepayment, int number){
 //(1+月利率)^(当前期数-1)
 BigDecimal temp = monthlyInterestRate.add(MoneyUtils.ONE).pow(number - 1);
 return principal.multiply(monthlyInterestRate)
   .subtract(monthlyRepayment)
   .multiply(temp).add(monthlyRepayment, MoneyUtils.MATHCONTEXT);
 }
 /**
 * <p>Description: 还款总利息。期数×贷款本金×月利率×(1+月利率)^期数÷〔(1+月利率)^期数-1〕-贷款本金 </p>
 * @param principal 贷款本金
 * @param monthlyInterestRate 月利率
 * @param amount 还款期数
 * @return
 */
 public static BigDecimal interest(BigDecimal principal, BigDecimal monthlyInterestRate, int amount){
 //(1+月利率)^期数
 BigDecimal temp = monthlyInterestRate.add(MoneyUtils.ONE).pow(amount);
 return new BigDecimal(amount)
   .multiply(principal)
   .multiply(monthlyInterestRate)
   .multiply(temp)
   .pide(temp.subtract(MoneyUtils.ONE), MoneyUtils.MATHCONTEXT)
   .subtract(principal, MoneyUtils.MATHCONTEXT);
 }
 /**
 * <p>Description: 月还款本金。已经精确到分位,未做单位换算</p>
 * @param principal 贷款本金
 * @param monthlyInterestRate 月利率
 * @param monthlyRepayment 月还款额
 * @param number 当前期数
 * @return
 */
 public static BigDecimal monthlyPrincipal(BigDecimal principal, BigDecimal monthlyInterestRate, BigDecimal monthlyRepayment, int number){
 BigDecimal monthInterest = monthlyInterest(principal, monthlyInterestRate, monthlyRepayment, number);
 //月还款额-月还款利息
 return monthlyRepayment.subtract(monthInterest).setScale(MoneyUtils.MONEYSHOWSCALE, MoneyUtils.SAVEROUNDINGMODE);
 }
 /**
 * <p>Description: 月还款本金。已经精确到分位,未做单位换算</p>
 * @param monthRepayment 月还款总额
 * @param monthInterest 月还款利息
 * @return
 */
 public static BigDecimal monthPrincipal(BigDecimal monthRepayment, BigDecimal monthInterest){
 //月还款总额-月还款利息
 return monthRepayment.subtract(monthInterest).setScale(MoneyUtils.MONEYSHOWSCALE, MoneyUtils.SAVEROUNDINGMODE);
 }
}
Copy after login

Interest first, then principal

import java.math.BigDecimal;

  /**
  * <p>Title: 先息后本还款方式工具类型</p>
  */
  public class BIAPPUtils extends RepaymentUtils {

    /**
    * <p>Description: 月还款利息 贷款本金×月利率 </p>
    * @param loan 贷款本金
    * @param monthlyInterestRate 月利率
    * @return
    */
    public static BigDecimal monthlyInterest(BigDecimal loan, BigDecimal monthlyInterestRate){
      return loan.multiply(monthlyInterestRate, MoneyUtils.MATHCONTEXT);
    }
    /**
    * <p>Description: 还款总利息 贷款本金×月利率×期数</p>
    * @param loan 贷款本金
    * @param monthlyInterestRate 月利率
    * @param number 期数
    * @return
    */
    public static BigDecimal interest(BigDecimal loan, BigDecimal monthlyInterestRate, int number){
      return loan.multiply(monthlyInterestRate).multiply(new BigDecimal(number), MoneyUtils.MATHCONTEXT);
    }
    /**
    * <p>Description: 月还款额</p>
    * @param loan 贷款本金
    * @param monthlyInterestRate 月利率
    * @param amount 期数
    * @param curNumber 当前期数
    * @return
    */
    public static BigDecimal monthlyRepayment(BigDecimal loan, BigDecimal monthlyInterestRate, int amount, int curNumber){
        BigDecimal monthlyInterest = monthlyInterest(loan, monthlyInterestRate);
        if(amount == curNumber){
          return monthlyInterest.add(loan, MoneyUtils.MATHCONTEXT);//最后月还款额
        }else{
          return monthlyInterest;
        }
    }
  }
Copy after login

*Amount calculation tools

import java.math.BigDecimal;
  import java.math.MathContext;
  import java.math.RoundingMode;
  import java.text.NumberFormat;

  public class MoneyUtils {
    /**
    * 标度(小数位数)
    */
    public static final int SCALE = 10;

    /**
    * 金钱显示标度(小数位数)
    */
    public static final int MONEYSHOWSCALE = 2;

    /**
    * 利率显示标度(小数位数)
    */
    public static final int INTERESTRATESHOWSCALE = 4;

    /**
    * 精度
    */
    public static final int PRECISION = 30;

    /**
    * 保存舍入规则
    */
    public static final RoundingMode SAVEROUNDINGMODE = RoundingMode.HALF_UP;

    /**
    * 是否舍去小数点最后的零
    */
    public static boolean STRIPTRAILINGZEROS = true;

    /**
    * 运算上下文(设置精度、舍入规则)
    */
    public static final MathContext MATHCONTEXT = new MathContext(PRECISION, SAVEROUNDINGMODE);

    /**
    * 每年天数
    */
    public static final String YEARDAYS = "360";

    /**
    * 每年月数
    */
    public static final String YEARMOTHS = "12";

    /**
    * 每月天数
    */
    public static final String MOTHDAYS = "30";

    /**
    * 数字“1”
    */
    public static final BigDecimal ONE = new BigDecimal(1);

    /**
    * 数字“100”
    */
    public static final BigDecimal HUNDRED = new BigDecimal(100);

    /**
    * 数字“0.01”
    */
    public static final BigDecimal ONEHUNDREDTH = new BigDecimal(0.01);

    public static BigDecimal newBigDecimal(String str){
      return (str == null || str.trim().isEmpty()) ? BigDecimal.ZERO : new BigDecimal(str);
    }

    /**
    * <p>Description: 加法返回格式化结果数字</p>
    * @param addend
    * @param augend
    * @return
    */
    public static BigDecimal add(BigDecimal addend, BigDecimal augend){
      return formatMoney(addend.add(augend, MATHCONTEXT));
    }

   /**
    * <p>Description: 加法返回格式化结果数字</p>
    * @param addend
    * @param augend
    * @return
    */
    public static BigDecimal add(String addend, String augend){
      BigDecimal decimalAddend = newBigDecimal(addend);
      BigDecimal decimalAugend = newBigDecimal(augend);
      return formatMoney(decimalAddend.add(decimalAugend, MATHCONTEXT));
    }

    /**
    * <p>Description: 加法返回格式化结果字符串</p>
    * @param addend
    * @param augend
    * @return
    */
    public static String addToString(BigDecimal addend, BigDecimal augend){
      return formatToString(addend.add(augend, MATHCONTEXT));
    }

    /**
    * <p>Description: 加法返回格式化结果字符串</p>
    * @param addend
    * @param augend
    * @return
    */
    public static String addToString(String addend, String augend){
      BigDecimal decimalAddend = newBigDecimal(addend);
      BigDecimal decimalAugend = newBigDecimal(augend);
      return formatToString(decimalAddend.add(decimalAugend, MATHCONTEXT));
    }

    /**
    * <p>Description: 减法返回格式化结果数字</p>
    * @param minuend
    * @param subtrahend
    * @return
    */
    public static BigDecimal subtract(BigDecimal minuend, BigDecimal subtrahend){
      return formatMoney(minuend.subtract(subtrahend, MATHCONTEXT));
    }

    /**
    * <p>Description: 减法返回格式化结果数字</p>
    * @param minuend
    * @param subtrahend
    * @return
    */
    public static BigDecimal subtract(String minuend, String subtrahend){
      BigDecimal decimalMinuend = newBigDecimal(minuend);
      BigDecimal decimalSubtrahend = newBigDecimal(subtrahend);
      return formatMoney(decimalMinuend.subtract(decimalSubtrahend, MATHCONTEXT));
    }

    /**
    * <p>Description: 减法返回格式化结果字符串</p>
    * @param minuend
    * @param subtrahend
    * @return
    */
    public static String subtractToString(BigDecimal minuend, BigDecimal subtrahend){
      return formatToString(minuend.subtract(subtrahend, MATHCONTEXT));
    }
    /**
    * <p>Description: 减法返回格式化结果字符串</p>
    * @param minuend
    * @param subtrahend
    * @return
    */
    public static String subtractToString(String minuend, String subtrahend){
      BigDecimal decimalMinuend = newBigDecimal(minuend);
      BigDecimal decimalSubtrahend = newBigDecimal(subtrahend);
      return formatToString(decimalMinuend.subtract(decimalSubtrahend, MATHCONTEXT));
    }

    /**
    * <p>Description: 乘法返回格式化结果数字</p>
    * @param multiplier
    * @param multiplicand
    * @return
    */
    public static BigDecimal multiply(BigDecimal multiplier, BigDecimal multiplicand){
      return formatMoney(multiplier.multiply(multiplicand, MATHCONTEXT));
    }

    /**
    * <p>Description: 乘法返回格式化结果数字</p>
    * @param multiplier
    * @param multiplicand
    * @return
    */
    public static BigDecimal multiply(String multiplier, String multiplicand){
      BigDecimal decimalMultiplier = newBigDecimal(multiplier);
      BigDecimal decimalMultiplicand = newBigDecimal(multiplicand);
      return formatMoney(decimalMultiplier.multiply(decimalMultiplicand, MATHCONTEXT));
    }

    /**
    * <p>Description: 乘法返回格式化结果字符串</p>
    * @param multiplier
    * @param multiplicand
    * @return
    */
    public static String multiplyToString(BigDecimal multiplier, BigDecimal multiplicand){
      return formatToString(multiplier.multiply(multiplicand, MATHCONTEXT));
    }
    /**
    * <p>Description: 乘法返回格式化结果字符串</p>
    * @param multiplier
    * @param multiplicand
    * @return
    */
    public static String multiplyToString(String multiplier, String multiplicand){
      BigDecimal decimalMultiplier = newBigDecimal(multiplier);
      BigDecimal decimalMultiplicand = newBigDecimal(multiplicand);
      return formatToString(decimalMultiplier.multiply(decimalMultiplicand, MATHCONTEXT));
    }

    /**
    * <p>Description: 除法返回格式化结果数字</p>
    * @param pidend
    * @param pisor
    * @return
    */
    public static BigDecimal pide(BigDecimal pidend, BigDecimal pisor){
      return formatMoney(pidend.pide(pisor, MATHCONTEXT));
    }
    /**
    * <p>Description: 除法返回格式化结果数字</p>
    * @param pidend
    * @param pisor
    * @return
    */
    public static BigDecimal pide(String pidend, String pisor){
      BigDecimal decimalpidend = newBigDecimal(pidend);
      BigDecimal decimalpisor = newBigDecimal(pisor);
      return formatMoney(decimalpidend.pide(decimalpisor, MATHCONTEXT));
    }

    /**
    * <p>Description: 除法返回格式化结果字符串</p>
    * @param pidend
    * @param pisor
    * @return
    */
    public static String pideToString(BigDecimal pidend, BigDecimal pisor){
      return formatToString(pidend.pide(pisor, MATHCONTEXT));
    }

    /**
    * <p>Description: 除法返回格式化结果字符串</p>
    * @param pidend
    * @param pisor
    * @return
    */
    public static String pideToString(String pidend, String pisor){
      BigDecimal decimalpidend = newBigDecimal(pidend);
      BigDecimal decimalpisor = newBigDecimal(pisor);
      return formatToString(decimalpidend.pide(decimalpisor, MATHCONTEXT));
    }
    /**
    * <p>Description: 月利率计算</p>
    * @param yearInterestRate
    * @return
    */
    public static BigDecimal monthInterestRate(BigDecimal yearInterestRate){
      BigDecimal dayInterestRate = MoneyUtils.pide(yearInterestRate, YEARDAYS).setScale(5, RoundingMode.CEILING);
      System.err.println(dayInterestRate);
      BigDecimal monthInterestRate = dayInterestRate.multiply(newBigDecimal(MOTHDAYS));
      System.err.println(monthInterestRate);
      return monthInterestRate;
    }

    /**
    * <p>Description: 按既定小数位数格式化金额保存</p>
    * @param result
    * @return
    */
    public static BigDecimal formatMoney(BigDecimal result){
      return result.setScale(SCALE, SAVEROUNDINGMODE);
    }

    /**
    * <p>Description: 按既定小数位数格式化金额显示</p>
    * @param resultStr 要格式化的数
    * @param multiple 乘以的倍数
    * @return
    */
    public static String formatMoneyToShow(String resultStr, BigDecimal multiple){
      BigDecimal result = newBigDecimal(resultStr);
      return MoneyUtils.formatToString(MoneyUtils.formatMoneyToShow(result, multiple));
    }

    /**
    * <p>Description: 按既定小数位数格式化金额显示</p>
    * @param result 要格式化的数
    * @param multiple 乘以的倍数
    * @return
    */
    public static BigDecimal formatMoneyToShow(BigDecimal result, BigDecimal multiple){
      return result.multiply(multiple).setScale(MONEYSHOWSCALE, SAVEROUNDINGMODE);
    }

    /**
    * <p>Description: 按既定小数位数格式化利率显示</p>
    * @param result 要格式化的数
    * @param multiple 乘以的倍数
    * @return
    */
    public static BigDecimal formatInterestRateToShow(BigDecimal result, BigDecimal multiple){
      return result.multiply(multiple).setScale(INTERESTRATESHOWSCALE, SAVEROUNDINGMODE);
    }

    /**
    * <p>Description: 按既定小数位数格式化显示</p>
    * @param result 要格式化的数
    * @param scale 显示标度(小数位数)
    * @return
    */
    public static BigDecimal formatToShow(BigDecimal result, int scale){
      return result.setScale(scale, SAVEROUNDINGMODE);
    }

    /**
    * <p>Description: 格式化为字符串,进行去零不去零操作</p>
    * @param result
    * @return
    */
    public static String formatToString(BigDecimal result){
      if(result == null){
        return "";
      }else{
        return STRIPTRAILINGZEROS ? result.stripTrailingZeros().toPlainString() : result.toPlainString();
      }
    }

    /**
    * <p>Description: 按既定小数位数格式化为货币格式</p>
    * @param result
    * @return
    */
    public static String formatToCurrency(BigDecimal result){
      BigDecimal temp = result.pide(HUNDRED, SAVEROUNDINGMODE);
      NumberFormat numberFormat = NumberFormat.getCurrencyInstance();
      return numberFormat.format(STRIPTRAILINGZEROS ? temp.stripTrailingZeros() : temp);
    }

    public static String formatToPercent(BigDecimal result){
      BigDecimal temp = result.pide(HUNDRED, SAVEROUNDINGMODE);
      NumberFormat numberFormat = NumberFormat.getPercentInstance();
      return numberFormat.format(STRIPTRAILINGZEROS ? temp.stripTrailingZeros() : temp);
    }

    /** 
    * <p>Description:格式化数字为千分位显示; </p>
    * @param text 
    * @return 
    */ 
    public static String fmtMicrometer(String text){ 
      DecimalFormat df = null; 
      if(text.indexOf(".") > 0) { 
        if(text.length() - text.indexOf(".")-1 == 0){ 
          df = new DecimalFormat("###,##0."); 
        }else if(text.length() - text.indexOf(".")-1 == 1){ 
          df = new DecimalFormat("###,##0.0"); 
        }else { 
          df = new DecimalFormat("###,##0.00"); 
        } 
      }else{ 
        df = new DecimalFormat("###,##0.00"); 
      } 
      double number = 0.0; 
      try { 
        number = Double.parseDouble(text); 
      } catch (Exception e) { 
        number = 0.0; 
      } 
      return df.format(number); 
    }
  }
Copy after login

The above is the detailed content of Sample code sharing for monthly equal payment and interest first and cost later calculation in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP: The Foundation of Many Websites PHP: The Foundation of Many Websites Apr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

See all articles