1

I'm trying to write code that would solve the following problem:

Nathan loves cycling.

Because Nathan knows it is important to stay hydrated, he drinks 0.5 litres of water per hour of cycling.

You get given the time in hours and you need to return the number of litres Nathan will drink, rounded to the smallest value.

For example:

time = 3 ----> litres = 1

time = 6.7---> litres = 3

time = 11.8--> litres = 5

Here's the code I have:

function litres(time) {
  var litrez = Math.round(time * 0.5);
  if (litrez === 1) {
    return "1 litre";
  }
  else {
    return litrez + " litres";
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="in"/>
<button onclick="$('#out').append(litres(Number($('#in').val())))"> Calculate</button>
<div id="out"></div>

Thanks in advance! :)

4 Answers 4

2

Math.round() rounds to the nearest integer, not the smallest value which said in the question. You may need Math.floor().

Sign up to request clarification or add additional context in comments.

Comments

0

To get the value in Integer, you may use Math.floor or Math.ceil. In this case you can you Math.floor to get the less than or equal value in Integer.

https://www.w3schools.com/jsref/jsref_floor.asp

Comments

0

Like Geno Chen said, you need to use Math.floor:

function litres(time) {
  var litrez = Math.floor(time * 0.5);
  if (litrez === 1) {
    return "1 litre";
  }
  else {
    return litrez + " litres";
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="in"/>
<button onclick="$('#out').append(litres(Number($('#in').val())))"> Calculate</button>
<div id="out"></div>

Math.round() rounds either up or down to the nearest integer (whole number). It'll round up if the number's fractional component is bigger or equal to .5, and down if its not.

Math.floor() rounds a number down to it's nearest integer that's lower or equal to itself, or as you said 'to the smallest value.'

Math.ceil() rounds a number up to it's nearest integer greater than itself.

Comments

-1

You mistake provide too complicated answer:

function litres(time) {
  return Math.floor(time * 0.5);
}

1 Comment

You omitted the unit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.