Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Always display at least two decimal places

I want to format a number so that it always have at least two decimal places.

Samples:

1
2.1
123.456
234.45

Output:

1.00
2.10
123.456
234.45
like image 689
skmasq Avatar asked Dec 09 '13 15:12

skmasq


People also ask

How do you display upto 2 decimal places?

format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.

How do I always show two decimal places in Python?

Use str. format() with “{:. 2f}” as string and float as a number to display 2 decimal places in Python. Call print and it will display the float with 2 decimal places in the console.

Does mynumb Force display of 2 decimal places?

This works for most case when "myNumb" has decimal. But it will not force display of the 2 decimal places if "myNumb" has less than 2 decimal places (3.2), or an integer (30) Show activity on this post.

Does ng-pattern Force display of the 2 decimal places?

But it will not force display of the 2 decimal places if "myNumb" has less than 2 decimal places (3.2), or an integer (30) Show activity on this post. Set the regular expression to validate the input using ng-pattern.

How to round off numbers to 2 decimal places in angular?

In most of the real world cases, we will round off numbers to 2 decimal places. So using decimal pipe we can easily format numbers in Angular upto 2 decimal points by passing digit info as x.2-2 (x is number of digits before decimal points)

What are the default options for decimal pipe?

As explained above if none of the decimal digit info is given, then decimal pipe will take default options, 1 interger value before decimal point and 3 fraction digits after decimal point. In the above code we are instructing decimal pipe to show atleast 3 integer values before decimal points and minimum 1 fraction digit, maximum 5 fraction digits.


2 Answers

You could fix to 2 or the count of current places;

 var result = num.toFixed(Math.max(2, (num.toString().split('.')[1] || []).length));
like image 86
Alex K. Avatar answered Sep 18 '22 03:09

Alex K.


How about using Intl :

Intl.NumberFormat(navigator.language, {
  minimumFractionDigits: 2,
  maximumFractionDigits: 10,
}).format(num)
like image 25
skube Avatar answered Sep 18 '22 03:09

skube