65 lines
2.2 KiB
TypeScript
65 lines
2.2 KiB
TypeScript
type DataFormProps = {
|
|
type: string;
|
|
column: string;
|
|
item: Record<string, unknown>;
|
|
}
|
|
|
|
export const roundNumber = (value : any, decimals: number) => {
|
|
if (typeof value === 'number') {
|
|
return addCommas((Math.round(value * Math.pow(10, decimals)) / Math.pow(10, decimals)).toFixed(decimals));
|
|
} else if (typeof value === 'string' && !isNaN(Number(value))) {
|
|
return addCommas(Number(value).toFixed(decimals));
|
|
}
|
|
}
|
|
|
|
export const addCommas = (value: string | number): any => {
|
|
if (typeof value === 'number') {
|
|
return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",").split('.').map((part, index) =>
|
|
index === 0 ? part : part.replace(/(\d{3})/g, '$1,')
|
|
).join('.');
|
|
} else if (typeof value === 'string') {
|
|
return value.includes('.')?value.split('.').map((part, index) =>
|
|
index === 0 ? part.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : part
|
|
).join('.'):String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
}
|
|
}
|
|
|
|
export default function DataForm({ type, column, item }: DataFormProps) {
|
|
if(item) {
|
|
const value = item[column];
|
|
switch(type){
|
|
case 'date':
|
|
if(value && typeof value === 'string' && value.length >= 8)
|
|
item[column] = value.substring(0, 4) + "-" + value.substring(4, 6) + "-" + value.substring(6, 8);
|
|
break;
|
|
case 'number':
|
|
if(value && value != '') {
|
|
item[column] = value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
}
|
|
break;
|
|
case 'float0':
|
|
if(value) {
|
|
item[column] = item[column] = String(value).includes('.')?String(Math.round(parseFloat(value.toString().replace(/,/g, '')) * 1) / 1).split('.').map((part, index) =>
|
|
index === 0 ? part.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : part
|
|
).join('.')
|
|
: String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
}
|
|
break;
|
|
case 'float1':
|
|
if(value) {
|
|
item[column] = roundNumber(value, 1);
|
|
}
|
|
break;
|
|
case 'float2':
|
|
if(value) {
|
|
item[column] = roundNumber(value, 2);
|
|
}
|
|
break;
|
|
case 'float3':
|
|
if(value) {
|
|
item[column] = roundNumber(value, 3);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
} |