JavaScript math, round to two decimal places in Jquery template
Asked Answered
B

6

5

I have some code

{{if commission}}              
    <td>${profit - commission}</td>   
{{else}}
    <td>${profit}</td>
{{/if}}

profit = 5;

commission = 2.145

result = 2.855999999999

I need 2.856

Please help me

I try to use (${profit - commission}).toFixed(2) - but it does not work.

Bonner answered 22/7, 2014 at 6:38 Comment(3)
Use a bignum library, floats for cash are trash.Directly
May be duplicate of #11833414Accumulate
How about ${(profit - commission).toFixed(2)}Teresaterese
D
13

Use simply toFixed(3) .it will select the 3 digits value after the dot value

var s=2.855999999999;
alert(s.toFixed(3))

OP: 2.856

DEMO

Dulcimer answered 22/7, 2014 at 6:43 Comment(0)
T
2
var result = 2.855999999999;
result =   result.toFixed(2); //returns string fixed to 2 decimal places
result =   parseFloat(result);//returns double 2 decimal places
alert(result);
Tandem answered 28/1, 2016 at 13:21 Comment(0)
E
2

Mentioned as using in jQuery template

parseFloat should be inside ${}

${ parseFloat(value).toFixed(2)}

{{if commission}}              
    <td>${parseFloat(profit - commission).toFixed(2)}</td>   
{{else}}
    <td>${profit}</td>
{{/if}}
Experimental answered 1/3, 2017 at 18:28 Comment(0)
Z
1

You can use:

var result = 2.855999999999;
result = Math.round(result * 1000) / 1000;
console.log(result ); //  ----> 2.856

Working Demo

Zoo answered 22/7, 2014 at 6:40 Comment(1)
Why Math.ceil()? 2.85511111111 will still yield 2.856.Teresaterese
F
0

Working fiddle here

You can use Math.round()

var num = 2.855999999999
num = Math.round(num * 1000) / 1000
alert(num);

Use 100 for .xx etc :D

Foreleg answered 22/7, 2014 at 6:44 Comment(0)
A
0

Try this:

parseFloat(${profit - commission}).toFixed(3);
Avellaneda answered 22/7, 2014 at 6:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.