本文主要是介绍【格式化数字、金额、千分位、保留几位小数、舍入舍去】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
工具函数
工具函数-uitil.js// 格式化数字、金额、千分位、保留几位小数、舍入舍去
export function numberFormat(number, decimals, dec_point, thousands_sep,roundtag) {/** 参数说明:* number:要格式化的数字* decimals:保留几位小数* dec_point:小数点符号* thousands_sep:千分位符号* roundtag:舍入参数,默认 "ceil" 向上取,"floor"向下取,"round" 四舍五入* */number = (number + '').replace(/[^0-9+-Ee.]/g, '');roundtag = roundtag || "ceil"; //"ceil","floor","round"var n = !isFinite(+number) ? 0 : +number,prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,dec = (typeof dec_point === 'undefined') ? '.' : dec_point,s = '',toFixedFix = function (n, prec) {var k = Math.pow(10, prec);console.log();return '' + parseFloat(Math[roundtag](parseFloat((n * k).toFixed(prec*2))).toFixed(prec*2)) / k;};s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');var re = /(-?\d+)(\d{3})/;while (re.test(s[0])) {s[0] = s[0].replace(re, "$1" + sep + "$2");}if ((s[1] || '').length < prec) {s[1] = s[1] || '';s[1] += new Array(prec - s[1].length + 1).join('0');}return s.join(dec);
}
示例<van-field label="采购金额" v-model="form.prchAmt" readonly><template #input><span>{{numberFormat(form.prchAmt, 2, ".", ",", "round")}}</span></template><van-button slot="button" size="small" disabled>元</van-button></van-field>
二、时间格式化
export default function formatMsgTime (timespan) {var dateTime = new Date(timespan) // 将传进来的字符串或者毫秒转为标准时间var year = dateTime.getFullYear()var month = dateTime.getMonth() + 1var day = dateTime.getDate()var hour = dateTime.getHours()var minute = dateTime.getMinutes()// var second = dateTime.getSeconds()var millisecond = dateTime.getTime() // 将当前编辑的时间转换为毫秒var now = new Date() // 获取本机当前的时间var nowNew = now.getTime() // 将本机的时间转换为毫秒var milliseconds = 0var timeSpanStrmilliseconds = nowNew - millisecondif (milliseconds <= 1000 * 60 * 1) { // 小于一分钟展示为刚刚timeSpanStr = '刚刚'} else if (1000 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60) { // 大于一分钟小于一小时展示为分钟timeSpanStr = parseInt((milliseconds / (1000 * 60))) + '分钟前'} else if (1000 * 60 * 60 * 1 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24) { // 大于一小时小于一天展示为小时timeSpanStr = parseInt(milliseconds / (1000 * 60 * 60)) + '小时前'} else if (1000 * 60 * 60 * 24 < milliseconds && milliseconds <= 1000 * 60 * 60 * 24 * 15) { // 大于一天小于十五天展示位天timeSpanStr = parseInt(milliseconds / (1000 * 60 * 60 * 24)) + '天前'} else if (milliseconds > 1000 * 60 * 60 * 24 * 15 && year === now.getFullYear()) {timeSpanStr = month + '-' + day + ' ' + hour + ':' + minute} else {timeSpanStr = year + '-' + month + '-' + day + ' ' + hour + ':' + minute}return timeSpanStr
}使用formatMsgTime(item.createTime, '{y}-{m}-{d} {h}:{i}')
这篇关于【格式化数字、金额、千分位、保留几位小数、舍入舍去】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!