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
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 %.
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.
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.
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.
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)
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.
You could fix to 2 or the count of current places;
var result = num.toFixed(Math.max(2, (num.toString().split('.')[1] || []).length));
How about using Intl :
Intl.NumberFormat(navigator.language, {
minimumFractionDigits: 2,
maximumFractionDigits: 10,
}).format(num)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With