Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 391
  • Last Modified:

Decimal with 2 decimal places

I need to get a Decimal into a format with 2 decimal places and without a currency sign (like $). I have this (where amount is Decimal):
string myString = (String.Format ("{0:.##}", this.amount));
decimal decimalRounded = Decimal.Parse(this.amount.ToString("0.00"));
return decimalRounded;

Open in new window

but I still get numbers like 1234.5, not 1234.50.
How can this be done?
0
allelopath
Asked:
allelopath
  • 3
1 Solution
 
Craig WagnerSoftware ArchitectCommented:
You can't really format a "Decimal", you can only format it when you turn it into a string. When it is in its numeric form then 1234.5 is accurate. If you want to display that number as 1234.50 then you need to do what you're already doing, which is String.Format it.
0
 
sarabhaiCommented:
decimal d = 1234.5678;
d = decimal.Round(d, 2);
Console.WriteLine("decimal variable d value: {0}", d); // Prints 1234.57
0
 
allelopathAuthor Commented:
@sarabhai:
The first line in the code snippet doesn't compile:
Cannot convert source type 'double' to target type 'decimal'
0
 
allelopathAuthor Commented:
@CraigWagner:
I see what you are saying. So I created a getter to return a string:
public string AmountString
{
    get
        {
            string myString = (String.Format("{0:.##}", this.amount));
            return myString;
    }
}
If the value has no decimal places, e.g. 1234, it returns 1234, not 1234.00
If it has 1 decimal place, e.g. 1234.1, it returns 1234.1, not 1234.10
0
 
allelopathAuthor Commented:
This works:
string myString = (String.Format("{0:0.00}", this.amount));
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now