ant-design-vue/components/statistic/Number.tsx

54 lines
1.5 KiB
TypeScript
Raw Normal View History

import padEnd from 'lodash-es/padEnd';
import { FunctionalComponent, VNodeTypes } from 'vue';
2020-10-17 11:51:17 +08:00
import { FormatConfig, valueType } from './utils';
2020-10-17 11:51:17 +08:00
interface NumberProps extends FormatConfig {
value: valueType;
}
const Number: FunctionalComponent<NumberProps> = props => {
const { value, formatter, precision, decimalSeparator, groupSeparator = '', prefixCls } = props;
let valueNode: VNodeTypes;
2020-10-17 11:51:17 +08:00
if (typeof formatter === 'function') {
// Customize formatter
valueNode = formatter({ value });
} else {
2020-10-17 11:51:17 +08:00
// Internal formatter
const val = String(value);
const cells = val.match(/^(-?)(\d*)(\.(\d+))?$/);
2020-10-17 11:51:17 +08:00
// Process if illegal number
if (!cells) {
valueNode = val;
} else {
const negative = cells[1];
let int = cells[2] || '0';
let decimal = cells[4] || '';
int = int.replace(/\B(?=(\d{3})+(?!\d))/g, groupSeparator);
if (typeof precision === 'number') {
decimal = padEnd(decimal, precision, '0').slice(0, precision);
}
if (decimal) {
decimal = `${decimalSeparator}${decimal}`;
}
2020-10-17 11:51:17 +08:00
valueNode = [
<span key="int" class={`${prefixCls}-content-value-int`}>
{negative}
{int}
</span>,
decimal && (
<span key="decimal" class={`${prefixCls}-content-value-decimal`}>
{decimal}
</span>
2020-10-17 11:51:17 +08:00
),
];
}
}
return <span class={`${prefixCls}-content-value`}>{valueNode}</span>;
};
2020-10-17 11:51:17 +08:00
export default Number;