简体   繁体   English

在 Android 中将 String/Double 转换为 Int

[英]Converting String/Double to Int in Android

Hello new to android/Java,你好,Android/Java 新手,

I am using JSON to Parse values as strings and doubles.我正在使用 JSON 将值解析为字符串和双精度值。 I am getting strings/doubles such as "6503.04" or "12.3942" etc. I am looking to see if I can convert these strings into an integer and also doubles into integers.我正在获取字符串/双精度数,例如“6503.04”或“12.3942”等。我想看看我是否可以将这些字符串转换为整数并将双精度数转换为整数。 I just need to get rid of the decimals points in the easiest way possible.我只需要以最简单的方式去掉小数点。 How can I make that happen?我怎样才能做到这一点?

Any help appreciated.任何帮助表示赞赏。

 double x = Double.parseDouble(your_string);
int y = (int) x;

y is going to have value of x with decimals cutted of. y 将有 x 的值,其中小数点被切除。

Before casting to int you are able to floor or ceil the number if you want.在转换为 int 之前,您可以根据需要对数字进行下限或上限。

Don't forget that parsing functions usually throw an exception when your_string is not a number.不要忘记,当 your_string 不是数字时,解析函数通常会抛出异常。

//get the value from json as double then get the integer //从json中获取双精度值然后获取整数

Double number = jsonObject.getDouble('longitude')
int newNumber = number.intValue()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM