当前位置:网站首页>String转为long 类型报错原因:要转为long必须是int、double、float型[通俗易懂]
String转为long 类型报错原因:要转为long必须是int、double、float型[通俗易懂]
2022-07-28 13:45:00 【全栈程序员站长】
大家好,又见面了,我是你们的朋友全栈君。
遇到该问题的解决办法一:
String strTime = "12.5416132";
double dblTime = Double.parseDouble(strTime);
long lngTime = new Double(dblTime).longValue();
log.info("lngTime:"+lngTime);具体报错原因请看下面的例子和解释:
上例子:
string a =100.1;
long b=long.parse(a);
转换时报 “输入字符串的格式不正确”
当a =100.0 时
long b=long.parse(a,NumberStyles.AllowDecimalPoint);
可以正常转换,
而 a=100.9 时
long b=long.parse(a,NumberStyles.AllowDecimalPoint);
转换失败,报超过Int64的最大值或最小值,原因解释:
问题一:long是整形也就是Int64类型,parse的对象必须是整形
问题二:
当a =100.0 时
long b=long.parse(a,NumberStyles.AllowDecimalPoint);
这是因为用了NumberStyles.AllowDecimalPoint
指示数字字符串可以具有小数点。 如果 NumberStyles 值包括 AllowCurrencySymbol 标志,分析的字符串包括货币符号,则小数分隔符字符由 NumberFormatInfo. CurrencyDecimalSeparator 属性确定。否则,小数分隔符由 NumberFormatInfo. NumberDecimalSeparator 属性来确定。
实际上是允许有小数点的出现,但作为long,还是不能parse非整数,此时的a是100.00,是可以丢去小数点作为整数的。也就是说long在parse的时候是默认把a处理后当成100来parse的。
问题三:
此时的a变成100.1,同样使用了NumberStyles.AllowDecimalPoint,但这时候long所parse的不再是一个整数,所以会提出异常,超过int64也就是long的范围,对于这个错误,可以先把a=100.1做一个转换变成整形,或者使用范围更广的double或decimal来parse,如decimal.Parse("100.1", NumberStyles.AllowDecimalPoint)例子和解释来源于点击打开链接
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/128601.html原文链接:https://javaforall.cn
边栏推荐
- HCIP第十二天
- 九、uni-popup用法 下拉框底部弹窗效果
- unittest执行runTestCase提示<_io.TextIOWrapper name=‘<stderr>‘ mode=‘w‘ encoding=‘utf-8‘>解决方案
- Alibaba, jd.com, Tiktok: push cloud to the heart of industry
- Open source project - taier1.2 release, new workflow, tenant binding simplification and other functions
- 十、时间戳
- Force deduction solution summary 1331 array sequence number conversion
- 一些企业数据平台建设的思考
- 2022 melting welding and thermal cutting examination questions and online simulation examination
- MeterSphere--开源持续测试平台
猜你喜欢

用友BIP CRM新品发布,赋能大中型企业营销增长

@Solution to DS ('slave') multi data source compatible transaction problem

MySQL development skills - View

Xcode编写SwiftUI代码时一个编译通过但导致预览(Preview)崩溃的小陷阱

9、 Uni popup usage popup effect at the bottom of the drop-down box

Development and definition of software testing

Thrift 序列化协议浅析
![[线程安全问题] 多线程到底可能会带来哪些风险?](/img/79/112ab7e586b0bceb296dfddb2728be.png)
[线程安全问题] 多线程到底可能会带来哪些风险?
C# 获取当前路径7种方法

树莓派基础 | 总结记录树莓派学习过程中的一些操作
随机推荐
bgp实验
围绕新市民金融聚焦差异化产品设计、智能技术提效及素养教育
ZABBIX distributed
十、时间戳
Custom Configuration Sections
2022高处安装、维护、拆除考试题库及在线模拟考试
【LeetCode】1331. 数组序号转换
8、 Picker usage drop-down box selection effect
@DS('slave') 多数据源兼容事务问题解决方案
Hcip day 10
pix2pix
[ecmascript6] other new interface features
7.27 simulation summary
Database optimization understanding these is enough
2022低压电工考试题及答案
草料二维码--在线二维码生成器
Node file operation
C# 获取当前路径7种方法
Four ways to create thread pools
Collaborative office tools: Online whiteboard is in its infancy, and online design has become a red sea