当前位置:网站首页>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
边栏推荐
- It's so hot that solar power can't take off? Hello, head
- 卡方分布和伽马函数(Chi-Square Distribution)
- [ecmascript6] modularization
- 利用反射构建一棵菜单生成树
- [ecmascript6] proxy and reflection
- IP black and white list
- Leetcode 1331. array sequence number conversion
- Bulk Rename Utility
- 如何只降3D相机不降UI相机的分辨率
- Unittest executes runtestcase prompt <_ io. Textiowrapper name= '< stderr>' mode=W encoding=UTF-8 > solution
猜你喜欢

MeterSphere--开源持续测试平台

Bulk Rename Utility

树莓派基础 | 总结记录树莓派学习过程中的一些操作

Revised version | target detection: speed and accuracy comparison (faster r-cnn, r-fcn, SSD, FPN, retinanet and yolov3)

Langjing Technology (Trax China) "robot +ai" opens the era of Chinese retail meta universe

Development and definition of software testing

It's so hot that solar power can't take off? Hello, head

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

如何有效进行回顾会议(上)?
随机推荐
2022 melting welding and thermal cutting examination questions and online simulation examination
[translation] how to choose a network gateway for your private cloud
Literature reading (245) roller
利用反射构建一棵菜单生成树
HCIP第十二天
jenkins
Super resolution reconstruction based on deep learning
2022年熔化焊接与热切割考题及在线模拟考试
[ecmascript6] async and await
Daily question - Scholarship
C# 读取ini文件、键值对操作
朗镜科技(Trax中国)“机器人+AI”开启中国零售元宇宙时代
【Utils】CookieUtil
Niuke multi school link with level editor i- (linear DP)
分集技术简略
468产品策划与推广方案(150份)
The default storage engine after MySQL 5.5 is InnoDB.
js的实例化方式
C语言库函数getchar()怎么使用
[ecmascript6] set and map