【发布时间】:2020-11-06 21:53:04
【问题描述】:
我有 2 个值
字符串纬度 = "37.348541"; 字符串经度 = "-121.88627";
我想像下面这样提取值,而不对值进行四舍五入。
纬度 = "37.34"; 经度=“-121.88”;
我尝试使用 DecimalFormat.format,但它做了一些四舍五入,我想提取一个确切的值。
【问题讨论】:
标签: java
我有 2 个值
字符串纬度 = "37.348541"; 字符串经度 = "-121.88627";
我想像下面这样提取值,而不对值进行四舍五入。
纬度 = "37.34"; 经度=“-121.88”;
我尝试使用 DecimalFormat.format,但它做了一些四舍五入,我想提取一个确切的值。
【问题讨论】:
标签: java
您可以使用String#substring 和String#indexOf 定义一个函数,如下所示:
public class Main {
public static void main(String[] args) {
// Tests
System.out.println(getNumberUptoTwoDecimalPlaces("37.348541"));
System.out.println(getNumberUptoTwoDecimalPlaces("-121.88627"));
System.out.println(getNumberUptoTwoDecimalPlaces("-121.8"));
System.out.println(getNumberUptoTwoDecimalPlaces("-121.88"));
System.out.println(getNumberUptoTwoDecimalPlaces("-121.889"));
}
static String getNumberUptoTwoDecimalPlaces(String number) {
int indexOfPoint = number.indexOf('.');
if (indexOfPoint != -1 && number.length() >= indexOfPoint + 3) {
return number.substring(0, indexOfPoint + 3);
} else {
return number;
}
}
}
输出:
37.34
-121.88
-121.8
-121.88
-121.88
【讨论】:
例如:
String latitude = "37.348541";
int i = latitude.indexOf(".");
if(i > 0 && i < latitude.length()-2) latitude = latitude.substring(i, i+2);
【讨论】:
您可以使用BigDecimal 类和ROUND_DOWN 选项。所以代码可能是这样的:
BigDecimal number = new BigDecimal("123.13298");
BigDecimal roundedNumber = number.setScale(2, BigDecimal.ROUND_DOWN);
System.out.println(roundedNumber);
否则,您还可以使用本机 double 和 Math.floor 或 Math.ceil 方法:
double number = 123.13598;
double roundedNumber = (number < 0 ? Math.ceil(number * 100) : Math.floor(number * 100)) / 100;
System.out.println(roundedNumber);
【讨论】: