我想格式化我的数字,总是显示2小数点后,四舍五入适用的地方。
例子:
number display
------ -------
1 1.00
1.341 1.34
1.345 1.35
我一直在用这个:
parseFloat(num).toFixed(2);
但是它把1显示为1,而不是1.00。
我想格式化我的数字,总是显示2小数点后,四舍五入适用的地方。
例子:
number display
------ -------
1 1.00
1.341 1.34
1.345 1.35
我一直在用这个:
parseFloat(num).toFixed(2);
但是它把1显示为1,而不是1.00。
当前回答
RegExp -替代方法
在输入时,你有字符串(因为你使用解析),所以我们可以通过只使用字符串操作和整数计算得到结果
let toFix2 = (n) = > n.replace (d / \(?) -(+)。\ \ \ \ d (d + 1) / (_), s, i、d (r) = {> 让k= (+r[0]>=5)+ +d - (r==5 && s=='-'); 返回s +(+i+(k>99)) + "。"(k +(> 99%) ? ? 9: 00”(k≥0 " k " + k)); }) / /测试 console.log toFix2(“1”)); console.log (toFix2 1.341”()); console.log (toFix2 1.345”()); console.log (toFix2 1.005”());
解释
s is sign, i is integer part, d are first two digits after dot, r are other digits (we use r[0] value to calc rounding) k contains information about last two digits (represented as integer number) if r[0] is >=5 then we add 1 to d - but in case when we have minus number (s=='-') and r is exact equal to 5 then in this case we substract 1 (for compatibility reasons - in same way Math.round works for minus numbers e.g Math.round(-1.5)==-1) after that if last two digits k are greater than 99 then we add one to integer part i
其他回答
我建议你用
new Intl.NumberFormat('de-DE', { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(num)
这样,您还将拥有指定国家的本地格式,并且它将确保显示精确的2个小数(无论num是1还是1.12345,它将分别显示1.00和1.12)
在这个例子中,我使用德语本地化,因为我想我的数字显示与千分隔符,所以这将是一些输出:
1 => 1,00
1.12 => 1,12
1.1234 => 1,12
1234 => 1.234,00
1234.1234 => 1.234,12
在进行toFixed()调用之前,我必须在parseFloat()和Number()转换之间做出决定。下面是一个捕获用户输入后进行数字格式化的示例。
HTML:
<input type="number" class="dec-number" min="0" step="0.01" />
事件处理程序:
$('.dec-number').on('change', function () {
const value = $(this).val();
$(this).val(value.toFixed(2));
});
上述代码将导致TypeError异常。注意,虽然html输入类型是“数字”,但用户输入实际上是“字符串”数据类型。但是,toFixed()函数只能在Number类型的对象上调用。
最终代码如下所示:
$('.dec-number').on('change', function () {
const value = Number($(this).val());
$(this).val(value.toFixed(2));
});
我倾向于使用Number() vs. parseFloat()强制转换的原因是,我不需要对空输入字符串或NaN值执行额外的验证。Number()函数将自动处理空字符串并将其转换为零。
你是这个意思吗?
@razu提供的答案是最好的。这是一个稍微重构的版本。
代码片段仍然不能返回类似showAsFloat(2.3346)的正确值(结果2.33,但应该是2.34)。所以,也看。
const showAsFloat = (input, decimals = 2, asString = false) => { if (input === null || input.constructor === Boolean || isNaN(+input)) { return input; } const converted = +( `${Math.round( parseFloat( `${input}e${decimals}` ) )}e-${decimals}` ); return asString ? converted.toFixed(decimals) : converted }; document.querySelector('#result').textContent = [ 'command | result', '-----------------------------------------------', 'showAsFloat(1); | ' + showAsFloat(1), 'showAsFloat(1.314); | ' + showAsFloat(1.314), 'showAsFloat(\'notanumber\') | ' + showAsFloat('notanumber'), 'showAsFloat(\'23.44567\', 3) | ' + showAsFloat('23.44567', 3), 'showAsFloat(2456198, 5, true)| ' + showAsFloat('24568', 5, true), 'showAsFloat(2456198, 5) | ' + showAsFloat('24568', 5), 'showAsFloat(0, 2, true); | ' + showAsFloat(0, 2, true), 'showAsFloat(1.345); | ' + showAsFloat(1.345), 'showAsFloat(0.005); | ' + showAsFloat(0.005), 'showAsFloat(null); | ' + showAsFloat(null), ].join('\n'); <pre id="result"></pre>
这里还有一个泛型函数,可以格式化到任何小数位数:
function numberFormat(val, decimalPlaces) {
var multiplier = Math.pow(10, decimalPlaces);
return (Math.round(val * multiplier) / multiplier).toFixed(decimalPlaces);
}
RegExp -替代方法
在输入时,你有字符串(因为你使用解析),所以我们可以通过只使用字符串操作和整数计算得到结果
let toFix2 = (n) = > n.replace (d / \(?) -(+)。\ \ \ \ d (d + 1) / (_), s, i、d (r) = {> 让k= (+r[0]>=5)+ +d - (r==5 && s=='-'); 返回s +(+i+(k>99)) + "。"(k +(> 99%) ? ? 9: 00”(k≥0 " k " + k)); }) / /测试 console.log toFix2(“1”)); console.log (toFix2 1.341”()); console.log (toFix2 1.345”()); console.log (toFix2 1.005”());
解释
s is sign, i is integer part, d are first two digits after dot, r are other digits (we use r[0] value to calc rounding) k contains information about last two digits (represented as integer number) if r[0] is >=5 then we add 1 to d - but in case when we have minus number (s=='-') and r is exact equal to 5 then in this case we substract 1 (for compatibility reasons - in same way Math.round works for minus numbers e.g Math.round(-1.5)==-1) after that if last two digits k are greater than 99 then we add one to integer part i