简体   繁体   English

Nullable的EditorFor <long> 将修剪分数

[英]EditorFor with Nullable<long> will trim fractions

I have the following model class inside my asp.net mvc web application :- 我的asp.net mvc Web应用程序中有以下模型类:-

[Display(Name="RAM (in GB)")]
        public Nullable<long> TOTALMEMORY { get; set; }

which represents total memery in bytes. 代表总记忆数(以字节为单位)。 now i need to convert bytes to GB , by doing the following on my controller class :- 现在我需要通过在控制器类上执行以下操作将字节转换为GB:

.MemoryInfo.TOTALMEMORY = (server.SystemInfo.MemoryInfo.TOTALMEMORY / (1024 * 1024 * 1024));

Then on the view the will display using the following two syntax as follow:- 然后在视图上,将使用以下两种语法显示以下内容:

@Html.EditorFor(model =>model.SystemInfo.MemoryInfo.VIRTUALMEMORY) 

OR 要么

@(Model.SystemInfo.MemoryInfo == null ? "" : Model.SystemInfo.MemoryInfo.TOTALMEMORY.ToString())

so in both way if the value in the DB is 8583778304 it will be displayed as 7 instead of 7.99 on the razor view ? 因此,以两种方式,如果数据库中的值是8583778304 ,它将在剃刀视图中显示为7而不是7.99 can anyone adivce what is the problem ? 任何人都可以出什么问题吗?

EDIT currently the 目前编辑

@Html.EditorFor(model =>model.SystemInfo.MemoryInfo.TotalMemoryGB)

will display 7.99426651000977 instead of 7.99 将显示7.99426651000977而不是7.99

while @(Model.SystemInfo.MemoryInfo == null ? "" : Model.SystemInfo.MemoryInfo.TotalMemoryGB.ToString()) will display 6.51925802230835E-09 . @(Model.SystemInfo.MemoryInfo == null ? "" : Model.SystemInfo.MemoryInfo.TotalMemoryGB.ToString())将显示6.51925802230835E-09。 so can you advice ? 那你可以建议吗?

TOTALMEMORY is a long value, which means it is an 64-bit integer. TOTALMEMORY是一个长值,表示它是一个64位整数。 It simply cannot house a decimal number like 7.99. 它根本无法容纳7.99这样的十进制数字。 And since you use integer division, it will always just trim the result, ie ignore everything after the decimal point. 并且由于使用整数除法,它将始终只修剪结果,即忽略小数点后的所有内容。

If the decimals are important to you, change it to a nullable double 如果小数点对您很重要,请将其更改为可为空的双精度数

public double? TOTALMEMORY { get; set; }

or even better, leave the field as is, to keep the EF mappings, and add a calculated property that connects to it: 甚至更好的是,保留该字段不变,以保留EF映射,并添加一个与其连接的计算属性:

public long? TOTALMEMORY { get; set; }

[Display(Name="RAM (in GB)")]
public double? TotalMemoryGB 
{
   get 
   {
       // The 1024.0 serves to force double division, instead of integer
       return TOTALMEMORY / 1024.0 / 1024.0 / 1024.0;
   }
   set 
   {
       TOTALMEMORY = (long) (value * 1024 * 1024 * 1024);
   } 
}

Now, in your UI you can use TotalMemoryGB exlusively, and work in gigabytes, while preserving the bytes in the database. 现在,您可以在UI中独家使用TotalMemoryGB,并以GB为单位工作,同时将字节保留在数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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