如何在不进行转换的情况下将double转换为long? [英] How to convert a double to long without casting?

查看:96
本文介绍了如何在不进行转换的情况下将double转换为long?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在不投标的情况下将双倍换算为长的最佳方法是什么?

What is the best way to convert a double to a long without casting?

例如:

double d = 394.000;
long l = (new Double(d)).longValue();
System.out.println("double=" + d + ", long=" + l);


推荐答案

假设你很满意截断为零,只是演员:

Assuming you're happy with truncating towards zero, just cast:

double d = 1234.56;
long x = (long) d; // x = 1234

这比通过包装类更快 - 更重要的是,它是更具可读性。现在,如果您需要舍入而不是始终为零,则需要稍微复杂的代码。

This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding other than "always towards zero" you'll need slightly more complicated code.

这篇关于如何在不进行转换的情况下将double转换为long?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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