How to decrease decimal places with EJS

Asked

Viewed 90 times

1

I am creating an application with Node.js, using the view engine EJS, and have a calculation of preço * quantidade, but the result is something like 80.9999999. Does anyone know how I can round this up using the EJS?

Follows the code:

<tbody>
                <% for (let i = 0; i < items.length; i++) { %>
                    <tr>
                        <td> <%= i+1 %> </td>
                        <td> <a href="/produto/<%= items[i].produtoId %>"><%= items[i].nome %></a> </td>
                        <td> R$ <%= items[i].preco %></td>
                        <form method="POST">
                            <td> <input type="text" name="quantidade" class="form-control" value="<%= items[i].quantidade %>"> </td>
                            <td>R$ <%= items[i].preco * items[i].quantidade %> </td> 
                            <td>
                                <input type="hidden" name="carrinhoId" value="<%= items[i]._id %>">
                                <input type="submit" class="btn btn-dark" value="Salvar" formaction="/carrinho/save">
                                <a class="btn btn-light" href="/verificar-pedido?pedido=<%= items[i]._id %>"> Pedido </a>
                                <input type="submit" class="btn btn-danger" value="Deletar" formaction="/carrinho/delete">
                            </td>

1 answer

3


EJS interprets expressions in Javascript. This way, you just need to use some global object rounding method Math.

For example:

<%= Math.round(items[i].preco * items[i].quantidade) %>

Another example outside the EJS:

console.log(Math.round(4.3)); // 4
console.log(Math.round(4.5)); // 5
console.log(Math.round(4.7)); // 5

console.log(Math.floor(4.5)); // 4
console.log(Math.ceil(4.5)); // 5

However, if you wish decrease to decimal places, without rounding, you can use the toFixed, present at the instance of any Number in Javascript. Note that this method will return a string, and not number.

For example:

const num = (45.56565656).toFixed(2)

console.log(num); // "45.56"
console.log(typeof num); // "string"

Then at EJS you can use:

<%= (items[i].preco * items[i].quantidade).toFixed(2) %>
//                                         ↑↑↑↑↑↑↑↑↑↑
  • 1

    It worked dude! Thank you so much!!! mainly for having explained the operation!

Browser other questions tagged

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