从java中的字符串解析带正/负前缀的数字 [英] Parse number with positive/negative prefix from string in java

查看:193
本文介绍了从java中的字符串解析带正/负前缀的数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在java中,从String中解析数字是非常简单的,即如果字符串的格式为'n'' - n',则使用Integer.parseInt(s) ,但不幸的是,它不能以'+ n'的格式解析字符串。

那么什么是最有效/优雅的解析方式如果它包含正面或负面的前缀,那么在java中的字符串的数字:'+ n'' - n'

解决方案

  Integer.parseInt(s.replace(+,)); 

实际上有很多使用Integer来解析数字的问题,因为Integer具有非常特定的边界的大小和格式(1,000,000.00)不解析这种方式,但我把你的问题作为Integer.parseInt满足你的需要就好了,你只需要处理您的数据+。 b $ b

It's quite straight forward in java to parse number from String, i.e. with Integer.parseInt(s) if string in the format 'n' or '-n', but unfortunately it fails to parse string in the format of '+n'.

So what is the most effective/elegant way to parse number from string in java if it contains positive or negative prefix: '+n' or '-n' ?

解决方案

Integer.parseInt(s.replace("+", ""));

In truth there are many gotchas using Integer to parse numbers like that, in that Integer has very specific bounds of size and format ("1,000,000.00") isn't parsing that way, but I'm taking your question as Integer.parseInt meets your needs just fine, you just have to deal with a + in your data.

这篇关于从java中的字符串解析带正/负前缀的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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