删除JS中的Alert总数内的小数点后2位的所有数字? (用于提醒总价值的功能)

时间:2019-02-24 18:48:56

标签: javascript

下面的代码段是我正在创建的购物车项目的基本结构,如果运行该代码段,您将看到带有该项目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>

2 个答案:

答案 0 :(得分:0)

您可以在此处的math.round中尝试以下代码:

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

答案 1 :(得分:0)

只需使用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