0

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
bourne2077
  • 161
  • 4
  • 15
  • 7
    You're confusing _rounding_ with _formatting_. Numbers, in every programming language, do not have trailing zeroes - that's just mathematics. What you're looking at in your debugger or output is the _default formatting_. Specify a different format to retain N-many trailing decimal places. – Dai Nov 28 '21 at 20:39
  • 6
    Look into `.toFixed(1)` – Kinglish Nov 28 '21 at 20:40
  • Does this answer your question? [How do you round to 1 decimal place in Javascript?](https://stackoverflow.com/questions/7342957/how-do-you-round-to-1-decimal-place-in-javascript) – H3AR7B3A7 Nov 28 '21 at 20:50

2 Answers2

2

You need to format your float result 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);
Marxys
  • 148
  • 7
1

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 ^^

dessei
  • 11
  • 1