简体   繁体   中英

Double with two Decimal Places

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?

Numbers which represent m.netary 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 m.netary 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.

You can truncate the number.

Truncate to decimal:

 Math.Truncate(valueToBeTruncated * 10) / 10;

Truncate to centesimal

 Math.Truncate(valueToBeTruncated * 100) / 100;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM