0

I got a minor brain-teaser thats keep bothering me. I'm unable to control the numbers of decimals written by my scripts.

HTML

<script type="text/JavaScript">
    <!--
    document.write($tekn_2_2/$tekn_2_1)
    //-->
</script>

JS

$tekn_2_1 = "28"
$tekn_2_2 = "7600"

I want this to return the value '271' instead of '271.42857142857144'. I apologize, I'm aware that this should be a small case, but I can get anything to work.

Munawir
  • 3,346
  • 9
  • 33
  • 51
Freshman
  • 293
  • 3
  • 8
  • 19

2 Answers2

2

Edit: Originally I had voted for toFixed but was not aware that this function also rounds. It looks like a simple floor is all that you need.

Math.floor($tekn_2_2/$tekn_2_1) == 271

Edit: +1 for Javascript: The Good Parts it goes over basic operations such as this. In a short but very informative manner.

http://www.amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/0596517742

jholloman
  • 1,959
  • 14
  • 16
-1
document.write(Math.round($tekn_2_2/$tekn_2_1));
srijan
  • 1,504
  • 1
  • 13
  • 24
  • This has the adverse affect of rounding up for some values instead of trimming off the decimal point. – jholloman Jan 15 '13 at 20:02
  • 1
    toFixed() returns string. From mathematical point of view, I won't convert any mathematical result directly to string just because I want to write it to document. More information if you want to discover pitfalls of toFixed - http://stackoverflow.com/questions/2861055/using-tofixed2-and-math-round-to-get-correct-rounding – srijan Jan 15 '13 at 20:06
  • Good point I didn't realize that toFixed also rounded. Looks like we were both wrong on that one then and Floor was the correct answer. – jholloman Jan 15 '13 at 20:20