Where to place a function "toFixed()` to round up the value?

Asked

Viewed 185 times

6

I would like to round off the final value of my code with the .toFixed() but I don’t know where to put.

Here is the code:

<script type="text/javascript">
function conversao(fahreinheit) {
    return (5/9) * (fahreinheit-32);
}
console.log(conversao(parseFloat(prompt('Entre com um grau em Fahreinheit: '))));
</script>
  • try to create a variable to store the value of your account and then apply . toFIxed() to the return variable

3 answers

7


We don’t either because it depends on what you want to do. Programming has literally a plethora of possibilities and most of them can produce the expected result. The first step to be able to program the desired result is to know exactly the result you want. Knowing more or less does not help much because it leaves many possibilities as valid, until discovering that in fact some of them are not so valid. Several may work, but not all of them are right for what they want. There is a lot of discussion about how to make a correct code, in this case the code is so done anyway and there are already errors that doesn’t make much difference, would learn more if you chose to do it in a more organized way, so I could say that this solves the problem, though not ideal:

function conversao(fahreinheit) {
    return (5/9) * (fahreinheit-32);
}
console.log(conversao(parseFloat(prompt('Entre com um grau em Fahreinheit: '))).toFixed(2));

I put in the Github for future reference.

Why did I choose to do this? Without a specification I think that the conversion function (which has a very bad name) should not worry about the number of decimals, after all it seems only want to do the calculation, in one place you may want to have 2 houses, in another you may want 1 or another want 4, or even kill the decimals. If there was a specification that the conversion would have to air a result with a number of houses or if the number of houses were parameterized, then I would have put inside the function.

2

You can put directly on the function return return ((5/9) * (fahreinheit-32)).toFixed();. Follows code:

<script type="text/javascript">
function conversao(fahreinheit) {
    return ((5/9) * (fahreinheit-32)).toFixed();
}
console.log(conversao(parseFloat(prompt('Entre com um grau em Fahreinheit: '))));
</script>

0

How the prompt returns the entered value you can do:

var p = prompt('Entre com um grau em Fahreinheit: ')
console.log(parseFloat(p).toFixed(2))

Browser other questions tagged

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