How to use javascript to perform math operation

Asked

Viewed 58 times

0

I have the following relationship

inserir a descrição da imagem aqui

How do I create a javascript code that counts decimals? For example... if I measure 5.7cm?

The account that would be: subtract 110 from 145 and the result divided by 10. That way I would have the value of each millimeter. Then just multiply by 7 (of 5.7cm) and add to the value in liters associated with 5cm, ie 110 liters.

The result would be 134.50 liters.

I needed a javascript code to do this account. Can someone help me in this nonsense?

  • Do you have these table numbers in text? for example in an object?

  • Welcome, please edit your question and add the code you are trying to... Consider taking a [tour] to get the most out of the community. Good luck;)

  • So... actually I want to do something really crazy. I don’t have much knowledge of java, so I made a Frankestein with some models I found on the internet. Basically what I wanted was to put the value in cm (including with the decimals 57,4 or 35,9 and etc.) and the page return me the corresponding value (liters). So far I have been able to pull the integers, but I need the decimals. See the project here https://gol-dolm.github.io/CalcD/

1 answer

0

Following your mathematical logic, you can use the Math.floor to obtain the rounded whole part below, and the Math.ceil to round up. Then use the % to extract the decimal part (with some extra code because Javascript needs to) and you have what you need!

An example would be:

// cm : litros
const escala = {
  "1": 10,
  "2": 28,
  "3": 51,
  "4": 79,
  "5": 110,
  "6": 145,
  "7": 182,
  "8": 222,
  "9": 265,
  "10": 310
};

function calcularLitragem(cm) {
  const valorInferior = Math.floor(cm);
  const valorSuperior = Math.ceil(cm);
  const parteDecimal = Number((cm % 1).toFixed(3));

  return escala[valorSuperior] - escala[valorInferior] / 10 * parteDecimal;
}
console.log(calcularLitragem(5)); // 110
console.log(calcularLitragem(5.7)); // 137.3
console.log(calcularLitragem(6)); // 145

  • I don’t have much knowledge of java, so I made a Frankestein with some models I found on the internet. Basically what I wanted was to put the value in cm (including with the decimals 57,4 or 35,9 and etc.) and the page return me the value (liters) corresponding. So far I’ve managed to pull the whole numbers, but I need the decimals. See the project here https://gol-dolm.github.io/CalcD/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.