Format number to always show 2 decimal places
(Math.round(num * 100) / 100).toFixed(2);
Live Demo
var num1 = "1";document.getElementById('num1').innerHTML = (Math.round(num1 * 100) / 100).toFixed(2);
var num2 = "1.341";document.getElementById('num2').innerHTML = (Math.round(num2 * 100) / 100).toFixed(2);
var num3 = "1.345";document.getElementById('num3').innerHTML = (Math.round(num3 * 100) / 100).toFixed(2);
span { border: 1px solid #000; margin: 5px; padding: 5px;}
<span id="num1"></span><span id="num2"></span><span id="num3"></span>
How can I format a decimal to always show 2 decimal places?
I suppose you're probably using the Decimal()
objects from the decimal
module? (If you need exactly two digits of precision beyond the decimal point with arbitrarily large numbers, you definitely should be, and that's what your question's title suggests...)
If so, the Decimal FAQ section of the docs has a question/answer pair which may be useful for you:
Q. In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used?
A. The quantize() method rounds to a fixed number of decimal places. If the Inexact trap is set, it is also useful for validation:
>>> TWOPLACES = Decimal(10) ** -2 # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
...
Inexact: None
The next question reads
Q. Once I have valid two place inputs, how do I maintain that invariant throughout an application?
If you need the answer to that (along with lots of other useful information), see the aforementioned section of the docs. Also, if you keep your Decimal
s with two digits of precision beyond the decimal point (meaning as much precision as is necessary to keep all digits to the left of the decimal point and two to the right of it and no more...), then converting them to strings with str
will work fine:
str(Decimal('10'))
# -> '10'
str(Decimal('10.00'))
# -> '10.00'
str(Decimal('10.000'))
# -> '10.000'
How do I display a decimal value to 2 decimal places?
decimalVar.ToString("#.##"); // returns ".5" when decimalVar == 0.5m
or
decimalVar.ToString("0.##"); // returns "0.5" when decimalVar == 0.5m
or
decimalVar.ToString("0.00"); // returns "0.50" when decimalVar == 0.5m
How to print a float with 2 decimal places in Java?
You can use the printf
method, like so:
System.out.printf("%.2f", val);
In short, the %.2f
syntax tells Java to return your variable (val
) with 2 decimal places (.2
) in decimal representation of a floating-point number (f
) from the start of the format specifier (%
).
There are other conversion characters you can use besides f
:
d
: decimal integero
: octal integere
: floating-point in scientific notation
Using String Format to show decimal up to 2 places or simple integer
An inelegant way would be:
var my = DoFormat(123.0);
With DoFormat
being something like:
public static string DoFormat( double myNumber )
{
var s = string.Format("{0:0.00}", myNumber);
if ( s.EndsWith("00") )
{
return ((int)myNumber).ToString();
}
else
{
return s;
}
}
Not elegant but working for me in similar situations in some projects.
HTML5 Number Input - Always show 2 decimal places
Solved following the suggestions and adding a piece of jQuery to force the format on integers:
parseFloat($(this).val()).toFixed(2)
How to display two digits after decimal point in SQL Server
select cast(your_float_column as decimal(10,2))
from your_table
decimal(10,2)
means you can have a decimal number with a maximal total precision of 10 digits. 2 of them after the decimal point and 8 before.
The biggest possible number would be 99999999.99
Formatting a number with exactly two decimals in JavaScript
To format a number using fixed-point notation, you can simply use the toFixed method:
(10.8).toFixed(2); // "10.80"
var num = 2.4;
alert(num.toFixed(2)); // "2.40"
Note that toFixed()
returns a string.
IMPORTANT: Note that toFixed does not round 90% of the time, it will return the rounded value, but for many cases, it doesn't work.
For instance:
2.005.toFixed(2) === "2.00"
UPDATE:
Nowadays, you can use the Intl.NumberFormat
constructor. It's part of the ECMAScript Internationalization API Specification (ECMA402). It has pretty good browser support, including even IE11, and it is fully supported in Node.js.
const formatter = new Intl.NumberFormat('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
console.log(formatter.format(2.005)); // "2.01"
console.log(formatter.format(1.345)); // "1.35"
Make an html number input always display 2 decimal places
So if someone else stumbles upon this here is a JavaScript solution to this problem:
Step 1: Hook your HTML number input box to an onchange
event
myHTMLNumberInput.onchange = setTwoNumberDecimal;
or in the html code if you so prefer
<input type="number" onchange="setTwoNumberDecimal" min="0" max="10" step="0.25" value="0.00" />
Step 2: Write the setTwoDecimalPlace method
function setTwoNumberDecimal(event) {
this.value = parseFloat(this.value).toFixed(2);
}
By changing the '2' in toFixed
you can get more or less decimal places if you so prefer.
Two Decimal places using c#
If you want to round the decimal, look at Math.Round()
Related Topics
Getting the Class Name of an Instance
Elegant Ways to Support Equivalence ("Equality") in Python Classes
Convert Integer to String in Python
Main() Function Doesn't Run When Running Script
Creating Dataframe from a Dictionary Where Entries Have Different Lengths
Convert Array of Indices to One-Hot Encoded Array in Numpy
How to Find the Exact Intersection of a Curve (As Np.Array) with Y==0
Pandas: Multiple Conditions While Indexing Data Frame - Unexpected Behavior
Create a Directly-Executable Cross-Platform Gui App Using Python
How to Calculate the Date Six Months from the Current Date Using the Datetime Python Module
How to State in Requirements.Txt a Direct Github Source
Pandas Read_Csv: Low_Memory and Dtype Options
Intuition and Idea Behind Reshaping 4D Array to 2D Array in Numpy
How to Implement an Ordered, Default Dict
How to Detach Matplotlib Plots So That the Computation Can Continue