Using String Format to Show Decimal Up to 2 Places or Simple Integer

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.

String Format for up to 2 decimal places or simple integer and with thousand separator - C#

String.Format("{0:#,##0.##}", 123.0);

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 integer
  • o: octal integer
  • e: floating-point in scientific notation

How to nicely format floating numbers to string without unnecessary decimal 0's

If the idea is to print integers stored as doubles as if they are integers, and otherwise print the doubles with the minimum necessary precision:

public static String fmt(double d)
{
if(d == (long) d)
return String.format("%d",(long)d);
else
return String.format("%s",d);
}

Produces:

232
0.18
1237875192
4.58
0
1.2345

And does not rely on string manipulation.

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>

Show a number to two decimal places

You can use number_format():

return number_format((float)$number, 2, '.', '');

Example:

$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00

This function returns a string.

How to format numbers with two decimal places?

Using a DecimalFormat is a perfectly good way to format a number.

However, you have a deeper issue here, which is that you should never use a Float or Double to store a value that needs to be exact, such as money.

That's because Floats and Doubles are stored as binary fractions, not decimal fractions.  And just as you can't represent 1/3 exactly as a decimal fraction of any finite length (0.33333333333…), so you can't represent 1/10 exactly as a binary fraction (0.0001100110011…).  So most of the decimal numbers you want to store will get approximated and rounded to the nearest binary fraction that can be stored.  This isn't always obvious — when printing them out, they get rounded again to the nearest decimal fraction, and in many cases that ‘recovers’ the number you want — but there are many cases where it's noticeable, especially as the result of calculations.

You can see the effect in the Kotlin REPL:

>>> 0.1 + 0.2
res0: kotlin.Double = 0.30000000000000004

In this case, the binary fractions nearest to 0.1 and 0.2 sum to give a binary fraction that's nearer to 0.30000000000000004 than it is to 0.3.

(There are many existing questions on StackOverflow discussing this, such as here.)

So if you need your money values to be accurate (and you almost always do!), then you should store them some other way.  For example, if you only ever need two decimal places (i.e. the number of paise), then simply store the number of paise as an integer.  Or if you don't need to do any calculations, you could store the number as a string (which is otherwise a bad idea…).

However, the most general and flexible way in Kotlin (and Java) is to use BigDecimal.  That uses decimal fractions internally to represent any decimal number exactly, to any precision you need, and you can easily do calculations and other manipulations.

In Java, using it is awkward and long-winded, but Kotlin's operator overloading makes it very natural, e.g.:

>>> val p1 = "0.1".toBigDecimal()
>>> val p2 = "0.2".toBigDecimal()
>>> p1 + p2
res3: java.math.BigDecimal = 0.3

DecimalFormat supports it too:

>>> java.text.DecimalFormat("#,##0.00").format(p1 + p2)
res4: kotlin.String! = 0.30

(Note: do not create a BigDecimal from a Float or Double, as the damage will already have been done.  If you have an integer value, then start from an integer type such as Int or Long; otherwise, you'll need to start from a String to get an exact value.)



Related Topics



Leave a reply



Submit