Number.prototype.toLocaleString()

277 阅读1分钟

需求:¥ 在金额前面在这个不陌生了吧

合计:<show-price>20.00</show-price>
  • 然后就封装了个组件:
<template>
	<view class="d-flex line-h font-weight mb-1" :class="color"
	style="font-size: 30upx;">
			<view class="font a-self-start line-h font-weight-100"></view>
			<slot />
		</view>
</template>

<script>
	export default {
		props:{
			color:{
				type:String,
				default:"main-text-color"
			}
		}
	}
</script>

<style>
</style>

后来看到这个toLocaleString()方法 千分位分割 还能解决上面的功能

image.png

 // 中文用zh表示    

        // 1.数字分割
        const numOne = 123456789.123
        console.log(numOne.toLocaleString()); //123,456,789.123

        //2.toLocaleString() 数字转为百分比 12%
        const numTow = 0.12
        console.log(numTow.toLocaleString('zh', {
            style: 'percent'
        })); //12%

        //3.toLocaleString() 数字转为货币表示法
        const numThree = 1000000
        console.log(numThree.toLocaleString('zh', {
            style: 'currency',
            currency: 'cny'
        }));
        console.log(numThree.toLocaleString('zh', {
            style: 'currency',
            currency: 'cny',
            currencyDisplay: 'code'
        }));
        console.log(numThree.toLocaleString('zh', {
            style: 'currency',
            currency: 'cny',
            currencyDisplay: 'name'
        }));
        // 4.
        var number = 123456.789;
        // nu 扩展字段要求编号系统,e.g. 中文十进制
        console.log(number.toLocaleString('zh-Hans-CN-u-nu-hanidec'));
        // → 一二三,四五六.七八九

        // 限制三位有效数字
        console.log(number.toLocaleString('zh', {
            maximumSignificantDigits: 3
        }));
        // → 123,000

参考:developer.mozilla.org/zh-CN/docs/…