fe-learning
fe-learning copied to clipboard
将数字转换为人民币单位格式
请根据面向对象编程的思想,设计一个类型 Cash用于表达人民币,使得:
class Cash {
}
const cash1 = new Cash(105)
const cash2 = new Cash(66)
const cash3 = cash1.add(cash2)
const cash4 = Cash.add(cash1, cash2)
const cash5 = new Cash(cash1 + cash2)
console.log(`${cash3}`, `${cash4}`, `${cash5}`)
// 1元7角1分 1元7角1分 1元7角1分
class Cash {
#money = 0
constructor(money = 0) {
if(typeof money !== 'number') throw new Error('请输入数值')
this.#money = money
}
get money() {
return this.#money
}
add(money = 0){
if(money instanceof Cash) {
money = money.money
} else if(typeof money !== 'number') throw new Error('请输入数值')
return Cash.trans(this.#money + money)
}
static add(money = 0, money2 = 0) {
if(money instanceof Cash) {
money = money.money
}
if(money2 instanceof Cash) {
money2 = money2.money
}
if(typeof money !== 'number' || typeof money2 !== 'number') throw new Error('请输入数值')
return Cash.trans(money + money2)
}
static trans(money = 0) {
if(money === 0) return '0元'
let res = ''
const symb = ['分', '角', '元']
for (let i = 0; i < symb.length; i++) {
const t = (i === 2 ? money : money % 10)
res = (t === 0 ? '' : (t + symb[i])) + res
money = Math.floor(money / 10)
}
return res
}
valueOf() {
return this.#money
}
toString() {
return Cash.trans(this.#money)
}
}