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

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

问题描述

在不强制转换的情况下将 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天全站免登陆