admin管理员组

文章数量:1289633

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

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

Share Improve this question edited Sep 25, 2019 at 17:30 ngShravil.py 5,0583 gold badges19 silver badges32 bronze badges asked Sep 25, 2019 at 15:29 pcampanapcampana 2,7113 gold badges25 silver badges42 bronze badges 1
  • 3 Use the pipes, Luke angular.io/api/mon/DecimalPipe. If you need something smarter, you can create your own pipe very easily – ne1410s Commented Sep 25, 2019 at 15:30
Add a ment  | 

2 Answers 2

Reset to default 5

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./edit/angular-ozgii4?file=src/app/app.ponent.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./edit/angular-4tsk9g?file=src/app/app.ponent.ts

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.

本文标签: javascriptNumber precision in typescriptStack Overflow