I have a product page that is fetching products information and displaying the products on the page. The API returns three price points. I have to add them up and display the price rounded down to one decimal. I have a solution already working, but it only works if it's not a whole number.
22.7312
returns 22.7
, but 22.0
returns 22
. I would like to always show one decimal, even if it's a zero. This is my current solution. How can I change it so that it shows the one decimal, even if it's a zero?
Math.floor(
(parseFloat(product.price1['regionalPrice'])
parseFloat(product.price2['marketPrice'])
parseFloat(product.price3['localPrice'])
) * 10) / 10
CodePudding user response:
You need to convert your float result to string before display it with the .toFixed(x) method.
Here is a full code sample for this:
const p1 = parseFloat(product.price1['regionalPrice']);
const p2 = parseFloat(product.price2['marketPrice']);
const p3 = parseFloat(product.price3['localPrice']);
const price = Math.floor((p1 p2 p3) * 10) / 10;
const displayPrice = price.toFixed(1);
CodePudding user response:
You could try rounding your numbers with the number.toFixed() function where you pass 1 as a function argument.
I tried it and
num = 22; num = nums.toFixed(1); console.log(num)
prints out 22.0.
Hope that this is what you were looking for ^^