鸿蒙多功能工具箱开发实战(十五)-汇率换算与理财计算开发

前言

汇率换算和理财计算是财务工具的重要组成部分。本文将讲解汇率换算、理财收益计算、房贷车贷计算等功能实现。

一、汇率换算

1.1 汇率数据结构

export interface Currency {
  code: string       // 货币代码
  name: string       // 货币名称
  symbol: string     // 货币符号
  rate: number       // 对人民币汇率
}

export const CURRENCIES: Currency[] = [
  { code: 'CNY', name: '人民币', symbol: '¥', rate: 1 },
  { code: 'USD', name: '美元', symbol: '$', rate: 7.2 },
  { code: 'EUR', name: '欧元', symbol: '€', rate: 7.8 },
  { code: 'GBP', name: '英镑', symbol: '£', rate: 9.1 },
  { code: 'JPY', name: '日元', symbol: '¥', rate: 0.048 },
  { code: 'KRW', name: '韩元', symbol: '₩', rate: 0.0054 },
  { code: 'HKD', name: '港币', symbol: 'HK$', rate: 0.92 },
  { code: 'TWD', name: '新台币', symbol: 'NT$', rate: 0.22 }
]

export class ExchangeRateConverter {
  static convert(
    amount: number,
    fromCurrency: Currency,
    toCurrency: Currency
  ): number {
    // 先转换为人民币,再转换为目标货币
    const cnyAmount = amount * fromCurrency.rate
    return cnyAmount / toCurrency.rate
  }
}

二、理财计算

2.1 定期存款计算

export class DepositCalculator {
  /**
   * 计算定期存款收益
   */
  static calculate(params: {
    principal: number    // 本金
    rate: number         // 年利率(%)
    years: number        // 存期(年)
    compound: boolean    // 是否复利
  }): {
    interest: number     // 利息
    total: number        // 本息合计
    yearlyInterest: number[]  // 每年利息
  } {
    const yearlyInterest: number[] = []

    if (params.compound) {
      // 复利计算
      let current = params.principal
      for (let i = 0; i < params.years; i++) {
        const interest = current * params.rate / 100
        yearlyInterest.push(interest)
        current += interest
      }
      return {
        interest: current - params.principal,
        total: current,
        yearlyInterest
      }
    } else {
      // 单利计算
      const interest = params.principal * params.rate / 100 * params.years
      for (let i = 0; i < params.years; i++) {
        yearlyInterest.push(params.principal * params.rate / 100)
      }
      return {
        interest,
        total: params.principal + interest,
        yearlyInterest
      }
    }
  }
}

2.2 基金定投计算

export class FundInvestmentCalculator {
  /**
   * 计算基金定投收益
   */
  static calculate(params: {
    monthlyAmount: number   // 每月投入
    months: number          // 投资月数
    annualReturn: number    // 预期年化收益率(%)
  }): {
    totalInvest: number     // 总投入
    totalValue: number      // 最终价值
    totalReturn: number     // 总收益
    returnRate: number      // 收益率
  } {
    const monthlyReturn = params.annualReturn / 100 / 12
    const totalInvest = params.monthlyAmount * params.months

    // 定投终值公式
    const totalValue = params.monthlyAmount *
      ((Math.pow(1 + monthlyReturn, params.months) - 1) / monthlyReturn) *
      (1 + monthlyReturn)

    const totalReturn = totalValue - totalInvest
    const returnRate = totalReturn / totalInvest * 100

    return {
      totalInvest,
      totalValue: Math.round(totalValue * 100) / 100,
      totalReturn: Math.round(totalReturn * 100) / 100,
      returnRate: Math.round(returnRate * 100) / 100
    }
  }
}

三、贷款计算

3.1 等额本息计算

export class LoanCalculator {
  /**
   * 等额本息计算
   */
  static calculateEqualPayment(params: {
    principal: number    // 贷款本金
    annualRate: number   // 年利率(%)
    years: number        // 贷款年限
  }): {
    monthlyPayment: number   // 月供
    totalPayment: number     // 还款总额
    totalInterest: number    // 利息总额
    schedule: Array<any>     // 还款计划
  } {
    const monthlyRate = params.annualRate / 100 / 12
    const months = params.years * 12

    // 月供公式
    const monthlyPayment = params.principal *
      monthlyRate * Math.pow(1 + monthlyRate, months) /
      (Math.pow(1 + monthlyRate, months) - 1)

    const totalPayment = monthlyPayment * months
    const totalInterest = totalPayment - params.principal

    // 生成还款计划
    const schedule = this.generateSchedule(
      params.principal,
      monthlyRate,
      months,
      monthlyPayment
    )

    return {
      monthlyPayment: Math.round(monthlyPayment * 100) / 100,
      totalPayment: Math.round(totalPayment * 100) / 100,
      totalInterest: Math.round(totalInterest * 100) / 100,
      schedule
    }
  }

  /**
   * 等额本金计算
   */
  static calculateEqualPrincipal(params: {
    principal: number
    annualRate: number
    years: number
  }): {
    firstPayment: number    // 首月还款
    lastPayment: number     // 末月还款
    totalPayment: number
    totalInterest: number
    schedule: Array<any>
  } {
    const monthlyRate = params.annualRate / 100 / 12
    const months = params.years * 12
    const monthlyPrincipal = params.principal / months

    // 首月还款
    const firstPayment = monthlyPrincipal + params.principal * monthlyRate

    // 末月还款
    const lastPayment = monthlyPrincipal + monthlyPrincipal * monthlyRate

    // 总利息
    const totalInterest = (params.principal + monthlyPrincipal) * months / 2 * monthlyRate

    const totalPayment = params.principal + totalInterest

    return {
      firstPayment: Math.round(firstPayment * 100) / 100,
      lastPayment: Math.round(lastPayment * 100) / 100,
      totalPayment: Math.round(totalPayment * 100) / 100,
      totalInterest: Math.round(totalInterest * 100) / 100,
      schedule: []
    }
  }

  private static generateSchedule(
    principal: number,
    monthlyRate: number,
    months: number,
    monthlyPayment: number
  ): Array<any> {
    const schedule = []
    let remaining = principal

    for (let i = 1; i <= months; i++) {
      const interest = remaining * monthlyRate
      const principalPart = monthlyPayment - interest
      remaining -= principalPart

      schedule.push({
        month: i,
        payment: Math.round(monthlyPayment * 100) / 100,
        principal: Math.round(principalPart * 100) / 100,
        interest: Math.round(interest * 100) / 100,
        remaining: Math.max(0, Math.round(remaining * 100) / 100)
      })
    }

    return schedule
  }
}

四、界面实现

@Entry
@Component
struct LoanCalculatorPage {
  @State principal: string = '1000000'
  @State rate: string = '4.9'
  @State years: string = '30'
  @State result: any = null

  build() {
    Column() {
      NavBar({ title: '房贷计算器' })

      // 输入区域
      Column() {
        this.InputRow('贷款金额', this.principal, (v) => this.principal = v, '万元')
        this.InputRow('年利率', this.rate, (v) => this.rate = v, '%')
        this.InputRow('贷款年限', this.years, (v) => this.years = v, '年')
      }

      Button('计算')
        .onClick(() => this.calculate())

      if (this.result) {
        Column() {
          Text(`月供: ${this.result.monthlyPayment}`)
            .fontSize(24)
            .fontWeight(FontWeight.Bold)

          Row() {
            Text(`还款总额: ${this.result.totalPayment}`)
            Text(`利息总额: ${this.result.totalInterest}`)
          }
        }
      }
    }
  }

  private calculate() {
    this.result = LoanCalculator.calculateEqualPayment({
      principal: parseFloat(this.principal) * 10000,
      annualRate: parseFloat(this.rate),
      years: parseInt(this.years)
    })
  }
}

图1 汇率计算界面展示
在这里插入图片描述

五、高级理财计算

5.1 理财计算流程图

定期存款

基金定投

等额本息

等额本金

输入本金和利率

选择计算类型

计算复利

计算定投收益

计算月供

计算首月月供

返回本息合计

返回还款计划

5.2 复利计算

// 复利计算
function compoundInterest(
  principal: number,
  rate: number,
  years: number,
  frequency: number = 1
): number {
  const n = frequency * years
  const r = rate / frequency
  return principal * Math.pow(1 + r, n)
}

5.3 基金定投计算

function fundInvestment(params: {
  monthlyAmount: number
  months: number
  annualReturn: number
}): FundResult {
  const { monthlyAmount, months, annualReturn } = params
  const monthlyReturn = annualReturn / 12
  const totalCost = monthlyAmount * months
  const totalValue = monthlyAmount *
    ((Math.pow(1 + monthlyReturn, months) - 1) / monthlyReturn) *
    (1 + monthlyReturn)
  return { totalCost, totalValue, profit: totalValue - totalCost }
}

六、汇率换算优化

6.1 汇率缓存

class ExchangeRateCache {
  private static rates: Map<string, number> = new Map()
  private static lastUpdate: number = 0
  
  static async getRate(from: string, to: string): Promise<number> {
    const key = `${from}-${to}`
    return this.rates.get(key) || 1
  }
}

七、单元测试

describe('LoanCalculator', () => {
  it('should calculate equal payment correctly', () => {
    const result = LoanCalculator.calculateEqualPayment({
      principal: 1000000,
      annualRate: 0.049,
      years: 30
    })
    expect(result.monthlyPayment).toBeGreaterThan(0)
  })
})

八、小结

本文详细讲解了财务计算工具:

  1. ✅ 汇率换算与缓存
  2. ✅ 定期存款计算
  3. ✅ 基金定投计算
  4. ✅ 等额本息贷款
  5. ✅ 等额本金贷款
  6. ✅ 复利计算
  7. ✅ 单元测试覆盖

系列文章导航
下期预告:鸿蒙多功能工具箱开发实战(十六)-实时行情数据获取

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐