鸿蒙多功能工具箱开发实战(十五)-汇率换算与理财计算开发 鸿蒙多功能工具箱开发实战(十五)-汇率换算与理财计算开发前言汇率换算和理财计算是财务工具的重要组成部分。本文将讲解汇率换算、理财收益计算、房贷车贷计算等功能实现。一、汇率换算1.1 汇率数据结构exportinterfaceCurrency{code:string// 货币代码name:string// 货币名称symbol:string// 货币符号rate:number// 对人民币汇率}exportconstCURRENCIES: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}]exportclassExchangeRateConverter{staticconvert(amount:number,fromCurrency:Currency,toCurrency:Currency):number{// 先转换为人民币再转换为目标货币constcnyAmountamount*fromCurrency.ratereturncnyAmount/toCurrency.rate}}二、理财计算2.1 定期存款计算exportclassDepositCalculator{/** * 计算定期存款收益 */staticcalculate(params:{principal:number// 本金rate:number// 年利率%years:number// 存期年compound:boolean// 是否复利}):{interest:number// 利息total:number// 本息合计yearlyInterest:number[]// 每年利息}{constyearlyInterest:number[][]if(params.compound){// 复利计算letcurrentparams.principalfor(leti0;iparams.years;i){constinterestcurrent*params.rate/100yearlyInterest.push(interest)currentinterest}return{interest:current-params.principal,total:current,yearlyInterest}}else{// 单利计算constinterestparams.principal*params.rate/100*params.yearsfor(leti0;iparams.years;i){yearlyInterest.push(params.principal*params.rate/100)}return{interest,total:params.principalinterest,yearlyInterest}}}}2.2 基金定投计算exportclassFundInvestmentCalculator{/** * 计算基金定投收益 */staticcalculate(params:{monthlyAmount:number// 每月投入months:number// 投资月数annualReturn:number// 预期年化收益率%}):{totalInvest:number// 总投入totalValue:number// 最终价值totalReturn:number// 总收益returnRate:number// 收益率}{constmonthlyReturnparams.annualReturn/100/12consttotalInvestparams.monthlyAmount*params.months// 定投终值公式consttotalValueparams.monthlyAmount*((Math.pow(1monthlyReturn,params.months)-1)/monthlyReturn)*(1monthlyReturn)consttotalReturntotalValue-totalInvestconstreturnRatetotalReturn/totalInvest*100return{totalInvest,totalValue:Math.round(totalValue*100)/100,totalReturn:Math.round(totalReturn*100)/100,returnRate:Math.round(returnRate*100)/100}}}三、贷款计算3.1 等额本息计算exportclassLoanCalculator{/** * 等额本息计算 */staticcalculateEqualPayment(params:{principal:number// 贷款本金annualRate:number// 年利率%years:number// 贷款年限}):{monthlyPayment:number// 月供totalPayment:number// 还款总额totalInterest:number// 利息总额schedule:Arrayany// 还款计划}{constmonthlyRateparams.annualRate/100/12constmonthsparams.years*12// 月供公式constmonthlyPaymentparams.principal*monthlyRate*Math.pow(1monthlyRate,months)/(Math.pow(1monthlyRate,months)-1)consttotalPaymentmonthlyPayment*monthsconsttotalInteresttotalPayment-params.principal// 生成还款计划constschedulethis.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}}/** * 等额本金计算 */staticcalculateEqualPrincipal(params:{principal:numberannualRate:numberyears:number}):{firstPayment:number// 首月还款lastPayment:number// 末月还款totalPayment:numbertotalInterest:numberschedule:Arrayany}{constmonthlyRateparams.annualRate/100/12constmonthsparams.years*12constmonthlyPrincipalparams.principal/months// 首月还款constfirstPaymentmonthlyPrincipalparams.principal*monthlyRate// 末月还款constlastPaymentmonthlyPrincipalmonthlyPrincipal*monthlyRate// 总利息consttotalInterest(params.principalmonthlyPrincipal)*months/2*monthlyRateconsttotalPaymentparams.principaltotalInterestreturn{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:[]}}privatestaticgenerateSchedule(principal:number,monthlyRate:number,months:number,monthlyPayment:number):Arrayany{constschedule[]letremainingprincipalfor(leti1;imonths;i){constinterestremaining*monthlyRateconstprincipalPartmonthlyPayment-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)})}returnschedule}}四、界面实现EntryComponentstruct LoanCalculatorPage{Stateprincipal:string1000000Staterate:string4.9Stateyears:string30Stateresult:anynullbuild(){Column(){NavBar({title:房贷计算器})// 输入区域Column(){this.InputRow(贷款金额,this.principal,(v)this.principalv,万元)this.InputRow(年利率,this.rate,(v)this.ratev,%)this.InputRow(贷款年限,this.years,(v)this.yearsv,年)}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}元)}}}}}privatecalculate(){this.resultLoanCalculator.calculateEqualPayment({principal:parseFloat(this.principal)*10000,annualRate:parseFloat(this.rate),years:parseInt(this.years)})}}图1 汇率计算界面展示五、高级理财计算5.1 理财计算流程图定期存款基金定投等额本息等额本金输入本金和利率选择计算类型计算复利计算定投收益计算月供计算首月月供返回本息合计返回还款计划5.2 复利计算// 复利计算functioncompoundInterest(principal:number,rate:number,years:number,frequency:number1):number{constnfrequency*yearsconstrrate/frequencyreturnprincipal*Math.pow(1r,n)}5.3 基金定投计算functionfundInvestment(params:{monthlyAmount:numbermonths:numberannualReturn:number}):FundResult{const{monthlyAmount,months,annualReturn}paramsconstmonthlyReturnannualReturn/12consttotalCostmonthlyAmount*monthsconsttotalValuemonthlyAmount*((Math.pow(1monthlyReturn,months)-1)/monthlyReturn)*(1monthlyReturn)return{totalCost,totalValue,profit:totalValue-totalCost}}六、汇率换算优化6.1 汇率缓存classExchangeRateCache{privatestaticrates:Mapstring,numbernewMap()privatestaticlastUpdate:number0staticasyncgetRate(from:string,to:string):Promisenumber{constkey${from}-${to}returnthis.rates.get(key)||1}}七、单元测试describe(LoanCalculator,(){it(should calculate equal payment correctly,(){constresultLoanCalculator.calculateEqualPayment({principal:1000000,annualRate:0.049,years:30})expect(result.monthlyPayment).toBeGreaterThan(0)})})八、小结本文详细讲解了财务计算工具✅ 汇率换算与缓存✅ 定期存款计算✅ 基金定投计算✅ 等额本息贷款✅ 等额本金贷款✅ 复利计算✅ 单元测试覆盖系列文章导航下期预告鸿蒙多功能工具箱开发实战(十六)-实时行情数据获取