EditorFor可空<长>将削减部分 [英] EditorFor with Nullable<long> will trim fractions

查看:97
本文介绍了EditorFor可空<长>将削减部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的模型类我的asp.net MVC Web应用程序内: -

I have the following model class inside my asp.net mvc web application :-

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

这将重新presents以字节为单位的总memery。现在我需要的字节转换为GB,通过执行以下操作在我的控制器类: -

which represents total memery in bytes. now i need to convert bytes to GB , by doing the following on my controller class :-

.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) 

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

因此​​,在这两种方式,如果在DB值 8583778304 将被显示为 7 而不是 7.99 剃刀上看法?任何人都可以书于什么问题?

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 ? can anyone adivce what is the problem ?

修改
目前

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

将显示 7.99426651000977 而不是 7.99

,而 @(Model.SystemInfo.MemoryInfo == NULL:Model.SystemInfo.MemoryInfo.TotalMemoryGB.ToString())显示6.51925802230835E-09。所以你的建议?

while @(Model.SystemInfo.MemoryInfo == null ? "" : Model.SystemInfo.MemoryInfo.TotalMemoryGB.ToString()) will display 6.51925802230835E-09 . so can you advice ?

推荐答案

TOTALMEMORY 是一个长期的价值,这意味着它是一个64位整数。它根本无法容纳像7.99的十进制数。而且,由于你使用整数除法,这将永远只是修剪的结果,即忽略小数点后的一切。

TOTALMEMORY is a long value, which means it is an 64-bit integer. It simply cannot house a decimal number like 7.99. And since you use integer division, it will always just trim the result, i.e. ignore everything after the decimal point.

如果小数对你很重要,将其更改为可空双

If the decimals are important to you, change it to a nullable double

public double? TOTALMEMORY { get; set; }

甚至更好,因为就是离开现场,保持EF映射,并添加连接到它计算的属性:

or even better, leave the field as is, to keep the EF mappings, and add a calculated property that connects to it:

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);
   } 
}

现在,在你的UI可以使用TotalMemoryGB exlusively,而在千兆字节工作,同时$ P $数据库pserving字节。

Now, in your UI you can use TotalMemoryGB exlusively, and work in gigabytes, while preserving the bytes in the database.

这篇关于EditorFor可空&LT;长&GT;将削减部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆