user12276542
user12276542

Reputation:

What's Wrong with this Code for a Basic Javascript Math Function?

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! :)

Upvotes: 1

Views: 1222

Answers (4)

You mistake provide too complicated answer:

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

Upvotes: -1

Examath
Examath

Reputation: 176

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.

Upvotes: 0

Linh Nguyen
Linh Nguyen

Reputation: 947

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

Upvotes: 0

Geno Chen
Geno Chen

Reputation: 5214

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

Upvotes: 2

Related Questions