javascript - How to correctly display 2 decimals in Javascript?
问题描述
There is a problem on my site. My price on things is displayed with two decimals after dot, for example 1.12, when i select a lot of positions, the total price becomes 14.619999999999997, this is all displayed through the JS. How can I limit so that 2 characters are displayed after the dot? To make it all readable, for example 15.77
My code:
function click() {
$('.de .item').click(function() {
var i = parseFloat($(this).attr('data-id'));
var price = parseFloat($(this).find('.price').find('b').text());
if($(this).hasClass('active')) {
delete(items[i]);
$(this).removeClass('active');
cost -= price;
} else {
items[i] = {
classid : $(this).attr('data-classid'),
assetid : $(this).attr('data-assetid')
};
$(this).addClass('active');
cost += price;
}
$('#total_cost').text(cost);
$('#skins_selected').text(getCount(items));
});
}
Responsible for the conclusion of the total price $('#total_cost').text(cost);
I try this method $('#total_cost').text(cost).toFixed(2);
it doesn't want to work. And i try $('#total_cost') = parseFloat(text(cost)).toFixed(2);
it doesn't work too.
How can I make the output correctly?
解决方案
$('#total_cost').text(cost.toPrecision(2));
或者
function precise(num, precision = 2) {
return Number.parseFloat(num).toPrecision(precision);
}
$('#total_cost').text(precise(cost));
推荐阅读
- android - 如何解决任务':app:checkDebugDuplicateClasses'的执行失败
- java - 与用户交谈文本+图像并将其保存到 firebase 以便稍后显示。(如法定人数)
- javascript - 需要 React Hook Form 动态
- json - 颤振嵌套对象解析的json数组
- python - 散景 - 清除以前的“人物”条目(情节)
- android-studio - 使用 Windows 10 在 Android Studio 4.0 终端中键入问题
- javascript - 点击各种按钮时如何改变各种div的innerHTML?
- blas - `SSWAP` 的用例是什么?
- firebase - 如何修复未在 Flutter 项目中安装的 Cloud Firestore 包?
- ruby - 为 redmine 安装安装正确版本的 gem bundler