在JS中的警报总数中删除2个小数位置后的所有数字?(用于警报总价值的功能)



下面的代码段,是我要创建的购物车项目的基本结构,如果运行摘要,您将看到带有此项目x值的警报消息,该项目是十进制位置是我要删除的。在var total = 0上尝试了MATH.ROUND();没有成功。

我不确定在这里实现的最佳方法,四舍五入或完全剥离其他小数是可以的,我最终只希望定价看起来像R10.00< - 例如。

var shoppingCart = []; //{Product Name, Product Price}
var Item = function(name, price, qty){
	this.name = name;
	this.price = price;
	this.qty = qty;
};
function addItemToCart (name, price, qty) {
	for (var i in shoppingCart){
		if (shoppingCart[i].name === name) {
			shoppingCart[i].qty += qty;
			alert("You have added another item to your cart!, your current total is: R" + totalCart() + " Including VAT.");
			return;
		}
	}
	var item = new Item(name, price, qty);
	shoppingCart.push(item);
	alert("You have successfully added an item to your cart!, your current total is: R" + totalCart() + " Including VAT.");
};
function totalCart() {
	var totalCost = 0;
	for (var i in shoppingCart){
		totalCost += shoppingCart[i].price * shoppingCart[i].qty * 1.15;
	}
	return totalCost;
};
function clearCart() {
	shoppingCart = [];
};
@import url('https://fonts.googleapis.com/css?family=Titillium+Web');
body {
	font-family: 'Titillium Web', sans-serif;
}
.shop-item {
	border: solid lightgrey 0.1em;
	text-align: center;
	overflow: hidden;
}
.shop-item:hover {
	-webkit-transform: scale(0.99);
    -ms-transform: scale(0.99);
	transform: scale(0.99);
}
.shop-item ul {
	list-style: none;
	text-align: center;
}
.shop-item img {
	border-radius: 4px;
	margin: auto;
}
.shop-item img:hover {
	opacity: 0.5;
}
.shop-item-price {
	font-weight: bold;
	font-size: 1.5em;
}
.row {
	margin-left: auto;
	margin-right: auto;
}
<div class="row">
	<div class="column col-md-3 shadow p-3 mb-5 bg-white rounded shop-item">
		<h4 class="shop-item-name">Intel® Celeron® G4900</h4>
		<img class="shop-item-image" src="../Images/Celeron.gif">
		<ul class="shop-item-details">
			<li>Intel® Celeron® Processor G Series</li>
			<li>Cores : 2</li>
			<li>Threads : 2</li>
			<li>Base Frequency : 3.10GHz</li>
		</ul>
		<p class="shop-item-price">R699.00</p>	
		<button class="btn btn-info btn-sm">More details</button>
		<button class="btn btn-success btn-sm" onclick="addItemToCart('Intel Celeron G4900', 699, 1)">Add to cart</button>
</div>

只需使用 toFixed ...

let nb = 100/7;
console.log(nb);
console.log(nb.toFixed(2));

https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/number/tofixed

您可以在此处尝试此代码。

Math.round((num)*100) / 100

最新更新