format - number of decimal digits



  • I'm busy with a first attempt using jsreport for an invoice-kind of report. At the end of the report I'm calculating the total.

    (1) The sum sometimes has a small deviation. Example : 0.71 + 25.42 = 26.1300000000000000000003
    (2) I would like to be able to control the output format of my numbers

    (1) and (2) would be solved if i'm able to control the output format of my number ( let's say to 2 digits ). I'm new to jscript. I've been searching far an example or clue but without solution. Is there something out of the box I can use for number formatting or should I install an handlebars extension or ... ? ( on jsrender I found reference to .toFixed() but couldn't get this implemented )

    An example of my report can be found at :
    https://playground.jsreport.net/w/anon/wsWO2_ul


  • administrators

    hi!

    as you already found that result with extra digits in the decimals is because javascript math is based on floating-point, so yes you need to format the numbers.

    i think you can solve this with the .toFixed or by searching out there some logic to format the number, i did a search and found this. so i have updated your example with the usage of the two ways: https://playground.jsreport.net/w/bjrmatos/_eOIhKye

    between the two, the numberFormat helper is better because it offers some customization options for the decimals and the separators.



  • It seems like toFixed() is a better solution, but it is not! In some cases it will NOT round correctly. Also, Math.round() will NOT round correctly in some cases.

    To correct the rounding problem with the previous Math.round() and toFixed(), you can define a custom JavaScript rounding function that performs a "nearly equal" test to determine whether a fractional value is sufficiently close to a midpoint value to be subject to midpoint rounding. The following function return the value of the given number rounded to the nearest integer accurately.

    Number.prototype.roundTo = function(decimal) {
    return +(Math.round(this + "e+" + decimal) + "e-" + decimal);
    }

    var num = 9.7654;
    console.log( num.roundTo(2)); //output 9.77




Log in to reply
 

Looks like your connection to jsreport forum was lost, please wait while we try to reconnect.