java 将 String(代表十进制数)转换为 long

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13089837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 11:26:44  来源:igfitidea点击:

Convert String (representing decimal number) to long

javastringparsingconverterlong-integer

提问by temelm

I've googled around a bit but could not find examples to find a solution. Here is my problem:

我已经用谷歌搜索了一下,但找不到找到解决方案的例子。这是我的问题:

String s = "100.000";
long l = Long.parseLong(s);

The 2nd line of code which tries to parse the string 's' into a long throws a NumberFormatException.

尝试将字符串 's' 解析为 long 的第二行代码抛出NumberFormatException

Is there a way around this? the problem is the string representing the decimal number is actually time in milliseconds so I cannot cast it to int because I lose precision.

有没有解决的办法?问题是代表十进制数的字符串实际上是以毫秒为单位的时间,所以我不能将它转换为 int,因为我失去了精度。

回答by assylias

You could use a BigDecimal to handle the double parsing (without the risk of precision loss that you might get with Double.parseDouble()):

您可以使用 BigDecimal 来处理双重解析(没有可能会导致精度损失的风险Double.parseDouble()):

BigDecimal bd = new BigDecimal(s);
long value = bd.longValue();

回答by user902383

as i don't know is your 100.000 equals 100 or 100 000 i think safest solution which i can recommend you will be:

因为我不知道你的 100.000 是等于 100 还是 100 000 我认为我可以推荐你的最安全的解决方案是:

NumberFormat nf = NumberFormat.getInstance();
Number number = nf.parse("100.000");
long l = number.longValue();

回答by Kenogu Labz

'long' is an integer type, so the String parse is rejected due to the decimal point. Selecting a more appropriate type may help, such as a double.

'long' 是整数类型,因此字符串解析因小数点而被拒绝。选择更合适的类型可能会有所帮助,例如 double。

回答by Thomas

Just remove all spaceholders for the thousands, the dot...

只需删除数以千计的所有空格符,点...

s.replaceAll(".","");

回答by psabbate

You should use NumberFormat to parse the values

您应该使用 NumberFormat 来解析值

回答by jean joseph

We can use regular expression to trim out the decimal part. Then use parseLong

我们可以使用正则表达式来去掉小数部分。然后使用 parseLong

Long.parseLong( data.replaceAll("\..*", ""));

Long.parseLong( data.replaceAll("\..*", ""));

回答by Amit Deshpande

If you don't want to loose presision then you should use multiplication

如果你不想放松压力,那么你应该使用 multiplication

    BigDecimal bigDecimal = new BigDecimal("100.111");
    long l = (long) (bigDecimal.doubleValue() * 1000);<--Multiply by 1000 as it
                                                         is miliseconds
    System.out.println(l);

Output:

输出:

100111