Programming Questions

  • Newest
  • Popular Tags
  • Ask A Question
  • Dividing num2 by num1 can't get four decimal points
    Am I on the right track here? I can get it to work except I can't seem to make it always output with four decimal places. This is the questions: "Using the JavaScript language, have the function FormattedDivision(num1,num2) take both parameters being passed, divide num1 by num2, and return the result as a string with properly formatted commas and 4 significant digits after the decimal place. For example: if num1 is 123456789 and num2 is 10000 the output should be "12,345.6789". The output must contain a number in the one's place even if it is a zero. "
    function FormattedDivision(num1,num2) { 
    
      var num3 = num1/num2;
      num3 = num3.toFixed(4);
      num3 = parseFloat(num3);
    
      return num3; 
    
    }
    
    atmosphere312 posted this question on 1/28/14 | javascript, division
    Answers
  • +
  • 3
  • -
  • You'll be wanting to parse it as a string, no a floating point. So .toFixed() is the right start but you'll also need to use.toString() and add in some logic for the commas.
  • +
  • 2
  • -
  • In JavaScript, an easy way to get arbitrary number of decimal points is to scale the number up first, then do your rounding, then divide scale out again.
     var num3 = num1/num2;
     var num3 = Math.round(num3 * 10000) / 10000
    
  • +
  • 1
  • -
  • As a string split it at the . and then use string manipulation
    Log in to write an answer.