How to convert a double to long without casting?(如何在不强制转换的情况下将 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在不强制转换的情况下将 double 转换为 long


基础教程推荐
- 存储 20 位数字的数据类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13