2

i have a array coming from api like this

x = [0, 12.1, 23.45, 100.23, 13.99, 90, 0, 16.1]

i want each number with decimal point upto 2, like 0.00 or 12.10

what i did is

x = x.toFixed(x);

but this return string values not number, i need all values as numbers. i am not sure how i can get numbers after converting them to decimals.

someone suggest this code i tried but no success

x = +x.toFixed(2);

i tried parseFloat as well after toFixed but it shows in console its a number but its not, its actually a string.

i am trying this in angular2+ application in primeng table

9
  • 2
    It is not possible. Numbers do not have trailing zeros. That is why it is converted to a string. Commented Dec 13, 2018 at 21:48
  • mean we are at dead end ? Commented Dec 13, 2018 at 21:49
  • 3
    Use the numbers as they are, convert them to strings (via toFixed) only when you need to display them. Commented Dec 13, 2018 at 21:50
  • 2
    what are you trying to achive? I believe that you are in wrong direction Commented Dec 13, 2018 at 21:53
  • 2
    Why do you need the 0's if you're doing math on them? Mathematically, 1.0000000000 == 1. The only time you should need leading 0s or trailing decimal 0s is when you're displaying them, not operating on them; in which case, as @ibrahimmahrir said, make a string copy for display but operate on the original numbers. Commented Dec 13, 2018 at 21:53

1 Answer 1

3

you can use pipe on the html side

{{x | number:'1.1-3'}}

Reference: https://angular.io/api/common/DecimalPipe#example

PS: dont forget to add DecimalPipe inside your declarations

If your need is to use this on ts side then your solution would work

(15).toFixed(2) //15.00
Sign up to request clarification or add additional context in comments.

3 Comments

i think it should be {{x | number:'1.2-2'}}. the number of digits to the right of the decimal should always be 2.
i did tofixed but it return it as a string not number
anyway thanks, display with number is a good idea and it works :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.