Add trailing zero to decimal

Options

How can I add a trailing zero to a decimal so that is always returned as two decimal places? E.g. decimal in DB of 452.5 should be returned as 452.50. I tried the 'round' filter but it doesn't work.

Thanks.

Best Answer

  • Ray Deck
    Ray Deck Trusted Xano Expert ✭✭✭
    Answer ✓
    Options

    Yes that's largely true. As long as you are talking about a number on which you can perform numerical operations, you have - and want - limited control over its formatting. You format to fixed precision or what have you at the end. As a number, 452.5 is equal to 452.50. You are opinionated about the difference between the two not when you are doing math, but when you are doing representation which comes after the math. 452.5 becomes "452.50" via number.toFixed(2) in JS (or the equiv formula in WW) on the front end or using number_format in Xano

    There is an exception here for scientific data where the degree of precision matters - significant digits. But that's not just a drop-in: you would want to use a scientific library (probably in python).

Answers

  • Ray Deck
    Ray Deck Trusted Xano Expert ✭✭✭
    Options

    The number_format filter will let you retain those digits by converting the number to a string that shows with fixed precision.

  • dorian
    dorian Member
    Options

    Thanks @Ray Deck but then it's a string and I'd no longer be able to perform math on it in the front end? If that's true, then better to format it for display in the front end.

  • dorian
    dorian Member
    edited June 2023
    Options

    Thanks @Ray Deck. I actually used Co-Pilot in WeWeb (front-end) and this is what it came up with after I asked it to format as USD currency:

    // Format the sum as USD currency with commas and two decimals
    const formattedSum = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(sum);