如何使用双?可空类型与Math.Round在.NET [英] How to use Double? nullable type with Math.Round in .NET

查看:150
本文介绍了如何使用双?可空类型与Math.Round在.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做这样的事情,但是C#不接受这样的:

I want to do something like this but C# doesn't accept this:

    public static void setPrice(Double? value)
    {

        if (value != null) {
            this.TextBoxPrice.Text = Math.Round(value, 2).ToString();
        } else {
            this.TextBoxPrice.Text = "No Price";   
        }

    }

那么是否意味着使用可空类型双?在这个用例完全无用的?我可以使用什么呢?

So does it mean using nullable type Double? is completely useless in this use case ? What can I use then ?

更新:我做了一个mystypo我实际上意味着

Update: I made a mystypo I actually meant

    public static void setPrice(Double? value)

让我改正。

推荐答案

您正在使用的不是可空类型 - 双击是一个非空值类型,所以不能为空。这是你想要的:

You're not currently using a nullable type - Double is a non-nullable value type, so can never be null. This is what you want:

public static void setPrice(Double? value)
{

    if (value != null) {
        this.TextBoxPrice.Text = Math.Round(value.Value, 2).ToString();
    } else {
        this.TextBoxPrice.Text = "No Price";   
    }
}

在另一方面,你要的没有的被使用来重新present财务价值。这是不恰当的作为的的浮点类型。使用十进制(或十进制?)来代替。

On the other hand, you should not be using a double to represent financial values. It's inappropriate as a binary floating point type. Use decimal (or decimal?) instead.

(请注意,双击等同于可空<双>

如果你来自一个Java的背景,你可能期望双击来做个参考包装类型入手 - 这不是。在C#是一个简单的别名 System.Double ;他们是同一类型。

If you've come from a Java background, you may be expecting Double to be a reference "wrapper" type to start with - it's not. In C# double is simply an alias for System.Double; they're the same type.

这篇关于如何使用双?可空类型与Math.Round在.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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