vue 将字节转为需要的格式,如KB MB GB
使用组件
<nFormatter :num="scope.row.fileSize"></nFormatter>
转换组件
/**
* @Author: 858834013@qq.com
* @Name: nFormatter
* @Date: 2022-01-16
* @Desc: 字节格式化
*/
<template>
<div>
{{ value }}
</div>
</template>
<script>
export default {
name: 'DateFormat',
components: {},
props: {
num: {
type: Number,
default() {
return 0
}
}
},
computed: {
value: function() {
return this.nFormatter2(this.num, 3)
}
},
methods: {
nFormatter(num, digits) {
const si = [
{ value: 1, symbol: '' },
{ value: 1E3, symbol: 'K' },
{ value: 1E6, symbol: 'M' },
{ value: 1E9, symbol: 'G' },
{ value: 1E12, symbol: 'T' },
{ value: 1E15, symbol: 'P' },
{ value: 1E18, symbol: 'E' }
]
const rx = /\.0+$|(\.[0-9]*[1-9])0+$/
let i
for (i = si.length - 1; i > 0; i--) {
if (num >= si[i].value) {
break
}
}
return (num / si[i].value).toFixed(digits).replace(rx, '$1') + si[i].symbol
},
nFormatter2(num, digits) {
const rx = /\.0+$|(\.[0-9]*[1-9])0+$/
return (num / 1E6).toFixed(digits).replace(rx, '$1') + 'M'
}
}
}
</script>
<style lang="scss" scoped>
</style>