Reputation: 2681
I'm doing a website with angular, and I'm trying to sum two numbers and show them in a < div >
, but I don't know how to manage the precision.
For example, with the following code:
htlm:
<div>{{sum}}</div>
typescript:
sum = 9.9 + 1.3
The website shows the value 11.200000000000001
, when I would like to show 11.2
I have seen that the way to manage float operations is by using toFixed(1)
, and then I get the expecte 11.2
.
However, if I use toFixed(1)
, for the operation 10.0 + 1.0
I get 11.0
when I would like to obtain 11
So what I would like to have is the number with one decimal when there are decimals, and without decimals when there aren't decimals
Upvotes: 6
Views: 14446
Reputation: 15113
What you see is how floats are handled in Javascript. The usual way to handle this is:
1. toFixed
when you want to pad zeros right:
(9.9 + 1.3).toFixed(2);
2. toPrecision
when you don't need to pad right:
(9.9 + 1.3).toPrecision(2);
You would use either if defining your variable in your Angular Typescript file.
3. However, you may also want to format a number directly in the HTML template with the built-in decimal pipe:
{{ (9.9 + 1.3) | number : '1.1' }}
The decimal pipe has quite a few options, check the docs for more info.
Upvotes: 3
Reputation: 10975
To achieve expected result , use below ternary with modulo operator (%) to get the remainder after dividing with value 1 (11.2 % 1 = 0.2
and 11.0%1 = 0
)
<div>{{sum %1?sum.toFixed(1): sum}}</div>
sample working code for reference - https://stackblitz.com/edit/angular-ozgii4?file=src/app/app.component.html
Option2:
Use Math.abs
with toFixed(1)
if you expect adding positive numbers and for negative values , you will get positive value with this approach
<div>{{Math.abs(sum.toFixed(1))}}</div>
sample working code for reference - https://stackblitz.com/edit/angular-4tsk9g?file=src/app/app.component.ts
Upvotes: 5