介绍
最近公司改造老项目,要将数字类型的显示效果做统一处理;
一个一个改显然不现实,所以做了一个公共组件统一处理;
对数字格式的要求主要有:小数保留位数、是否显示千分符、小数位不足是否补零、小数截断模式
另外还附加一个显示效果 居中、居左、居右
还要分不同类型来控制,比如金额,数量使用不同格式;
主要功能类分为3个
- NumberExtensions.js // 数字格式配置,数字剪切,格式化等核心功能
- NumberExtensions.jQuery.js // 基于 jQuery 自动渲染 input 框
- NumberExtensions.Vue.js // 基于 Vue2 自定义组件 number-input (还有一部分页面是基于vue2做的)
源码:gitee
效果展示
目前功能已完成,效果如下:数字输入框JQuery版 demo源码预览下载- JSRUN





使用方法
$(function(){
/**
* 设置小数样式
* @param {String|String[]} styleKeys 样式名称和别名。如:["price","p"]
* @param {Object} config 配置。如: { decimals: 4, mode: "Round", thousands: true, zreofill: false, align: "left", units: {} };
* decimals: 小数保留位数 0~20
* mode: 小数截取方式 Round-四舍五入/Ceil-向上取整/Floor-向下取整
* thousands: 是否显示千分位 true/false
* zreofill: 小数位不足是否补零 true/false
* align: 对齐方式 left/right/center
* units: 单位配置
* @param {String} unit 单位
*/
Number.setConfig("price", "p"], { decimals: 4, mode: "Round", thousands: false, zreofill: false, align: "right" });
})
// 根据配置截取小数位数
var price = 1.234567.scale("p");
// 根据配置格式化数字字符串
var priceStr = 1234567.8.format("p");
// 同时操作截取和格式化
var str = number.scaleformat("p");
// 静态方法,可以在不确定变量类型的情况下编码
var str = Number.scaleformat(number,"p") || "-" //当参数number无法转为数字时,返回null
// Number.scale(number,"p")
// Number.format(number,"p")
// Number.parse 方法,方便转换数字,排除正负无穷,可正确处理千分符
var number = Number.parse('1,234,567.76') || 0;
基于 jQuery
<!-- number-style="price" 数字样式 -->
<!-- number-unit="元" 样式单位(可忽略) -->
<!-- number-strict 严格数字(丢失焦点时如果内容为非数字,可恢复上次正确的数字) -->
<!-- number-max="100" 数字内容最大不能大于该值 -->
<!-- number-min="0" 数字内容最大不能小于该值 -->
<input number-style="price" number-unit="元" number-strict number-max="100" number-min="0" />
<script>
$(function(){
// 设置数字格式,可结合实际情况从API中获取页面设置效果
Number.setConfig("price", "p"], { decimals: 4, mode: "Round", thousands: false, zreofill: false, align: "right" });
// 渲染页面
Number.render();
})
</script>
基于Vue
<div id="app">
<!-- 属性参考 jQuery 部分 -->
<number-input number-style="price" number-strict number-min="100" number-max="9999.99" v-model="price" />
</div>
<script>
// 设置数字格式,可结合实际情况从API中获取页面设置效果
Number.setConfig("price", "p"], { decimals: 4, mode: "Round", thousands: false, zreofill: false, align: "right" });
var app = new Vue({
el: '#app',
data: {
price: 12345
}
});
</script>
网友评论