console
const btn = document.getElementById('btn');
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
const res = document.getElementById('res');
const formatMoney = (money, unit, decimal) => {
if (typeof money === 'number' && money) {
return unit ? `${unit} ${money.toFixed(decimal)}` : money.toFixed(decimal);
} else if (typeof money === 'string' && money) {
return unit ? `${unit} ${parseFloat(money).toFixed(decimal)}` : parseFloat(money).toFixed(decimal);
} else {
return unit ? `${unit} 0.${'0'.padEnd(decimal, '0')}` : `0.${'0'.padEnd(decimal, '0')}`;
}
};
btn.addEventListener('click', function () {
console.log(formatMoney(250, '', 2))
res.innerHTML = formatMoney(250, '', 2)
});
btn1.addEventListener('click', function () {
console.log(formatMoney(250, '¥', 0))
res.innerHTML = formatMoney(250, '¥', 0)
});
btn2.addEventListener('click', function () {
console.log(formatMoney(250, '$', 2))
res.innerHTML = formatMoney(250, '$', 2)
});
<div class="tip">
<p class="title">数组排序</p>
<div>
点击右下角
<span class="sp">Console</span>
查看运行结果
</div>
</div>
<div>
<button id="btn">无单位</button>
<button id="btn1">¥单位</button>
<button id="btn2">保留2位小数</button>
</div>
<div id="res"></div>
.tip {
background-color: rgba(174,220,174,0.25);
padding: 0.75rem;
border-left: 0.35rem solid;
border-radius: 0.25rem;
margin: 1.5rem 0;
font-size: 0.9rem;
border-color: #5cb85c;
}
.title {
font-size: 18px;
font-weight: bolder;
margin-top: 0;
}
.sp {
background: orange;
}