-2

I have looked online and have found multiple examples that show you how to add 2 decimal places to a double.However all the examples i found require you to change the double to a string format. such as

c# double to string

formatting a double to two decimal places

Is it possible to assign two decimal places and have it remain as a double?

for example double(25,2)

public double balance {get;set}

double money=145

balance=money 

so the balance should now be 145.00

balance should remain a double(25,2)

josh
  • 29
  • 5
  • 1
    No. A double is defined as an 8-byte floating point number. It does not have a defined precision. See [Difference between decimal, float and double in .NET?](https://stackoverflow.com/q/618535/215552) for much more information. – Heretic Monkey May 21 '20 at 19:58
  • 2
    It's not hard to write a `struct` having two integer numbers for a whole part and a fractional part. If fractional part exceeds 100 you add `f / 100` to the whole part and you assign `f % 100` to the fractional part – Alexey S. Larionov May 21 '20 at 20:05
  • 2
    Use `decimal` not `double`. – i486 May 21 '20 at 20:07

2 Answers2

1

No. The best way to handle that is keep using a numeric type as long as possible, and then only convert to string at the last possible moment before showing the value to a user.

Additionally, whenever you work with money you should prefer the decimal type over double. This still won't let you keep the two decimal places — that's just not how numeric types work! — but it will help you avoid rounding errors that can really matter when working with money.

Finally, if this is your property:

public decimal Balance {get;set;}

You can have an additional property that looks like this

public string BalanceString {get {return Balance.ToString("F2");} }

Note this property has no set and depends on the numeric Balance property.

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
0

No. This is not possible. None of the .net data types are like this. Like oracle, where you can assign number(10,2). In .net you need to separate operations from display. Whatever your value is, you can always format it for display like

double money = 145.2345d;
Console.WriteLine(money.ToString("#.00"));

Result: 145.23 You can also use standard letter format options like "C"

Console.WriteLine(money.ToString("C"));

Result: $145.23

T.S.
  • 18,195
  • 11
  • 58
  • 78