I'm using The entity framework for creating a database with some products. Product Has a entity Named Price, i want to save all prices with two decimal places even if it's a round number.
Like:
2 = 2.00
5.9 = 5.90
17.99 = 17.99
I can't use Decimal
Here is my Product:
namespace CashRegister.Models
{
public class Produkt
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public double Preis { get; set; }
public bool Preisart { get; set; }
public bool Deaktiviert { get; set; } = false;
public List<EinkaufsPosition> EinkaufsPositionen { get; set; }
public int KategorieId { get; set; }
public Kategorie Kategorie { get; set; }
}
}
Is it possible to Save it in the Database Like I Showed and How?
CodePudding user response:
You can truncate the number.
Truncate to decimal:
Math.Truncate(valueToBeTruncated * 10) / 10;
Truncate to centesimal
Math.Truncate(valueToBeTruncated * 100) / 100;
CodePudding user response:
Numbers which represent monetary value should never be stored as floats or doubles. This is because floats and doubles are based on the binary system and as such cannot store some values exactly that do have an exact representation in decimal systems. If you ever need to do math with these values you will sooner or later encounter rounding errors.
Instead you should store monetary values in a decimal type, which can exactly represent them, or, even simpler, store them as cents in an integer type.
How many decimal digits you want to display is a job for the presentation layer, not the data storage layer.