Help to round value returned from function

Asked

Viewed 44 times

0

Hello, I would like the return of the variables to be only 2 decimal places, how do I do this?

<meta charset="UTF-8">
<h1>DESCONTO ETANOL</h1>

<script>

    function pulaLinha() {

        document.write("<br>");
    }

    function mostra(frase) {

        document.write(frase);
        pulaLinha();
        pulaLinha();
    }

    var valorDoAbastecimento = parseInt(prompt("Digite o valor do abastecimento")) ;

    var totalDeLitrosAbastecido = valorDoAbastecimento / 3.09

    var descontoPorLitro = 0.04 ;

    var totalDesconto = totalDeLitrosAbastecido * descontoPorLitro ;

    var dinheiroPago = parseInt(prompt("Digite o valor pago em dinheiro."));

    var valorTotalComDesconto = valorDoAbastecimento - totalDesconto

    var troco = dinheiroPago - valorTotalComDesconto;



    mostra ("<b>O total de litros abastecido é de: </b><mark>" + totalDeLitrosAbastecido + " Litros") ;
    mostra ("</mark><b>O valor do desconto nesta compra é de </b><mark>" + totalDesconto + " R$");
    mostra ("</mark><b>O troco do cliente é de </b><mark>" + troco + " R$");

</script>

2 answers

2

You can use two methods already ready, which are:

to) Number​.prototype​.toFixed();

b) Number​.prototype​.toLocale​String();

About the method Number​.prototype​.toFixed()

The method toFixed() format a number using fixed point notation. One string representing numObj which does not use exponential notation and has exactly digits after the decimal place. The number will be rounded if necessary, and zeros will be added to the part after the comma so that it has the size that has been specified. If the numObj is greater than 1e+21, then the method will be invoked Number.prototype.toString() and a string will be returned in exponential notation.

Example:

var numObj = 12345.6789;

numObj.toFixed();       // Retorna '12346': note o arredondamento, não possui nenhuma parte fracionária
numObj.toFixed(1);      // Retorna '12345.7': note o arredondamento
numObj.toFixed(6);      // Retorna '12345.678900': note que adicionou zeros
(1.23e+20).toFixed(2);  // Retorna '123000000000000000000.00'
(1.23e-10).toFixed(2);  // Retorna '0.00'
2.34.toFixed(1);        // Retorna '2.3'
2.35.toFixed(1);        // Retorna '2.4'. Note que arredonda para cima neste caso.
-2.34.toFixed(1);       // Retorna -2.3 (devido à precedência do operador, literais de números negativos não retornam uma string...)
(-2.34).toFixed(1);     // Retorna '-2.3' (...a menos que se utilize parênteses)

About the method Number​.prototype​.toLocale​String()

The method toLocaleString() returns a string with a language-sensitive representation of this number. The new arguments locales and options allow applications to specify the language whose formatting conventions will be used and customize the behavior of the function. In previous implementations, which ignored the arguments locales and options arguments, the location used and the way to return the string were totally dependent on the implementation.

Example:

var numero = 123456.789;

// O alemão usa vírgula como separador de decimal e ponto para milhares
console.log(numero.toLocaleString('de-DE'));
// → 123.456,789

// O árabe usa dígitos Árabes Orientais em muitos países que falam árabe
console.log(numero.toLocaleString('ar-EG'));
// → ١٢٣٤٥٦٫٧٨٩

// A Índia usa separadores de milhares/cem mil/dez milhões
console.log(numero.toLocaleString('en-IN'));
// → 1,23,456.789

// A chave de extensão nu requer um sistema de numeração, ex. decimal chinês
console.log(numero.toLocaleString('zh-Hans-CN-u-nu-hanidec'));
// → 一二三,四五六.七八九

// Quando informada uma língua sem suporte, como balinês,
// inclua uma língua reseva, neste caso indonésio
console.log(numero.toLocaleString(['ban', 'id']));
// → 123.456,789

Access the official sources below to learn more how the methods work, are super interesting and for different cases!

OFFICIAL SOURCE - DEVELOPER MOZILLA (Number . prototype . toLocale String())

OFFICIAL SOURCE - DEVELOPER MOZILLA (Number . prototype . toFixed())

0

Try to add this at the end of your code:

troco = troco.toFixed(2);
console.log(troco);

Browser other questions tagged

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