2

I am trying to display how much more a customer needs to spend in order to get free shipping on this website. I have the code working, but the output is not displayed as I expected. The price for the product is 29.99 but the result of the below handlebars code is returning the value 5.010000000000002. Is there a way in handlebars (or html) to display only the 5.01 and not the rest?

{{subtract 35 price.without_tax.value}}
Dancrumb
  • 26,597
  • 10
  • 74
  • 130
Jake P
  • 121
  • 1
  • 2
  • 9

2 Answers2

3

You can register an helper using registerHelper and use it for the conversion.

Handlebars.registerHelper('distanceFixed', function(distance) {
return distance.toFixed(2);
});

Demo: http://jsfiddle.net/IrvinDominin/T7knB/

Ajas Aju
  • 725
  • 7
  • 30
1

I don't have any experience with Handlebars, but I can tell you that in plain JavaScript, you would handle this with Number's toFixed() method.

var output = 35 - 29.99;

console.log(output); // 5.010000000000002
console.log(output.toFixed(2)); // 5.01
Travis
  • 12,001
  • 8
  • 39
  • 52
  • 1
    Why is it that 35-29.99 returns more than just 5.01? – Jake P Aug 04 '17 at 14:41
  • 1
    This is an issue with most all programming languages. It has to do with how floating point numbers are interpreted. For more information, I recommend this SO question: https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Travis Aug 04 '17 at 14:44
  • Looks like this is a platform issue for me as I cannot write my own helpers in Handlebars on BigCommerce. Will have to find something from their library of helpers, otherwise this would have worked. – Jake P Aug 04 '17 at 15:43