我创建了一个相当大的函数,它接受一个参数,并根据数字的大小,正确地格式化它。它对于具有typeof
数字的任何值都可以正常工作,但是有一些实例需要将字符串转换为数字值。如果parseInt
的类型不是number
,我会尝试使用console.log
。当我在第一个if语句之后typeof
时,它表示function formatNumber(number) {
if (typeof number !== 'number') {
number = parseInt(number);
return number;
}
let decimals = 2;
const isNegative = number < 0;
const rounded = (number >= 1e+6) ? Math.round(number) : number;
const isInteger = () => parseInt(number, 10) === parseFloat(number);
const abs = Math.abs(rounded);
if (abs < 1e+6) {
decimals = isInteger(abs) ? 0 : decimals;
}
const formatter = val => {
const string = Math.abs(val).toString();
let formatted = '';
for (let i = string.length - 1, d = 1; i >= 0; i--, d++) {
formatted = string[i] + formatted;
if (i > 0 && d % 3 === 0) {
formatted = `,${formatted}`;
}
}
return formatted;
};
const formatLargeNumbers = (value, decimalPlaces) => {
let adjustedValue;
if (value >= 1e+12) {
adjustedValue = parseFloat((value / 1e+12).toFixed(decimals));
return `<span title=${formatter(value)}>${adjustedValue}T</span>`;
}
if (value >= 1e+9) {
adjustedValue = parseFloat((value / 1e+9).toFixed(decimals));
return `<span title=${formatter(value)}>${adjustedValue}B</span>`;
}
if (value >= 1e+6) {
adjustedValue = parseFloat((value / 1e+6).toFixed(decimals));
return `<span title=${formatter(value)}>${adjustedValue}M</span>`;
}
if (value >= 1e+3 && value < 1e+6) {
return value.toLocaleString('en-EN', {
minimumFractionDigits: decimalPlaces,
maximumFractionDigits: decimalPlaces,
});
}
return value.toFixed(decimals);
};
if (isNegative) {
let negativeNumber = Math.abs(rounded);
if (negativeNumber >= 1e+3) {
negativeNumber = formatLargeNumbers(negativeNumber);
}
return `<span class="negative-value">(${negativeNumber})</span>`;
}
return formatLargeNumbers(rounded, decimals);
}
现在是数字。但是,当任何字符串通过时,例如“10000”,它只显示为10000,而不是具有正确格式的10,000的预期输出。下面是我的代码......有没有明显的方法可能会让我错了?
<a href="<?php echo base_url();?>index.php/registration/invoice/<?php echo base64_encode($rows['id']);?>">
function invoice()
{
$paymentid=base64_decode($this->uri->segment('3'));
$record=$this->Registration_model->get_data($paymentid);
}