String to Decimal With 2 Decimal Places Always

String to Decimal with 2 decimal places always

# is an optional digit when 0 is a mandatory digit

For instance

 decimal d = 12.3M;

// d with exactly 2 digits after decimal point
// d with at most 2 digits after decimal point


12.30   // exactly 2 digits after decimal point: fractional part padded by 0
12.3 // at most 2 digits after decimal point: one digit - 3 - is enough

Convert string to decimal to always have 2 decimal places

Decimal is a bit strange type, so, technically, you can do a little (and may be a dirty) trick:

// This trick will do for Decimal (but not, say, Double) 
// notice "+ 0.00M"
Decimal result = Convert.ToDecimal("25.5", CultureInfo.InvariantCulture) + 0.00M;

// 25.50

But much better approach is formatting (representing) the Decimal to 2 digits after the decimal point whenever you want to output it:

Decimal d = Convert.ToDecimal("25.50", CultureInfo.InvariantCulture);

// represent Decimal with 2 digits after decimal point

Number to String (Always 2 decimal Place)

try this method

double i=12.22222;             //first variable
double j=1.2545; //second variable
double h=i*j; // multiple first and second
string s=h.ToString("0.00"); // convert to string and proper format

this methed return


Convert string to decimal number with 2 decimal places in Java

This line is your problem:

litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));

There you formatted your float to string as you wanted, but but then that string got transformed again to a float, and then what you printed in stdout was your float that got a standard formatting. Take a look at this code

import java.text.DecimalFormat;

String stringLitersOfPetrol = "123.00";
System.out.println("string liters of petrol putting in preferences is "+stringLitersOfPetrol);
Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
stringLitersOfPetrol = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : "+stringLitersOfPetrol);

And by the way, when you want to use decimals, forget the existence of double and float as others suggested and just use BigDecimal object, it will save you a lot of headache.

How to parse float with two decimal places in javascript?

You can use toFixed() to do that

var twoPlacedFloat = parseFloat(yourString).toFixed(2)

Two Decimal places using c#

If you want to round the decimal, look at Math.Round()

Related Topics

Leave a reply