rounding decimal numbers of results in jquery

I've got this code -

$(document).ready(function() {
  $(function(){
$("#result").submit(function(e) {
   e.preventDefault();
   var ele = $("#element").val(),
    target = $("#target").val(),
    context = $("#context").val(),
    border = $("#border").val(),
    margin = $("#margin").val(),
    padding = $("#padding").val();

console.log(ele, target, context, border, margin, padding);

var DoubleMargin = parseInt(margin, 10) * 2;
var DoublePadding = parseInt(padding, 10) * 2;
var DoubleBorder = parseInt(border, 10) * 2;


var ActualTarget = parseInt(target, 10) - parseInt(DoubleBorder, 10) - parseInt(DoubleMargin, 10) - parseInt(DoublePadding, 10) * 1;
var result3 = parseInt(target, 10) - parseInt(DoubleMargin, 10) * 1;
var MarginResult = parseInt(margin, 10) / parseInt(target, 10) * 100;
var PaddingResult = parseInt(padding, 10) / parseInt(target, 10) * 100;
var OriginalResult = parseInt(ActualTarget, 10) / parseInt(context, 10) * 100;
var BorderResult = parseInt(target, 10) - parseInt(border, 10) * 1;

//$(".result").append(ele + " " + result + "%");
$("<p></p>", {
    html: ele + " {<br><span>width: " + OriginalResult + "%;" + " /* " + ActualTarget + " (originally " + target + ") / " + context + " */ " + "<br>border: " + border + "px; " + "<br>margin: " + MarginResult + "%; " + "<br>padding: " + PaddingResult+ "%;" + "<br> </span>}"
}).hide().appendTo("#code-results").fadeIn();
   });

}); 

});

and I want the results to round the decimal point to just 5 places. I think I should be using

var num.toFixed(5)

but I can't get it to work

any ideas?

edit: thanks for comments - basically the results for OriginalResult, MarginResult and Padding Result could have a result of 1.0204081632653061%; which I want to only have the first 5/6 fractional points so it's 1.020408% for example. Is there a 'catch all' than can be applied?

I've put it up on jsfiddle - http://jsfiddle.net/sturobson/xTEKm/37/ :)

2 Answers

  1. Michael- Reply

    2019-11-14

    Since we don't know where you're trying to use toFixed(), here's one example of how you could use it in your code:

    var OriginalResult = ((parseInt(ActualTarget, 10) / parseInt(context, 10)) * 100).toFixed(5);
    
  2. Mike- Reply

    2019-11-14

    Given that num is a percentage, and could be, as described in the comments: 1.0204081632653061% it's being returned as a string. Therefore you need to call parseFloat(), in order to retrieve the floating-point number, before you call toFixed():

    var num = '1.0204081632653061%';
    var numTruncated = parseFloat(num).toFixed(5);
    

    JS Fiddle demo;

    References:

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>