我们正在使用一个返回值为20.000-
的服务。尾随-
表示负数。这是他们的标准。
如何在不进行字符串操作的情况下将其解析为double。我正在寻找解析它的直接方式。
答案 0 :(得分:1)
您必须操纵字符串,以便首先提取负号:
std::get_temporary_buffer
答案 1 :(得分:1)
我从中看到了两件事。
话虽如此,试一试:
public static void main(String[] args) throws Exception {
String data = "20.123456-";
// Determine if positive or negative
boolean negative = data.charAt(data.length() - 1) == '-';
double dblData = negative
? Double.parseDouble(data.substring(0, data.length() - 1)) * -1
: Double.parseDouble(data);
// Determine precision
long precision = 0;
if (data.contains(".")) {
String decimalPart = data.split("\\.")[1];
// 0x30 and 0x39 are the hex values for characters 0 - 9
precision = decimalPart.chars().filter(c -> 0x30 <= c && c <= 0x39).count();
}
NumberFormat nf = new DecimalFormat();
nf.setMinimumFractionDigits((int)precision);
// Display results
System.out.println(nf.format(dblData));
}
结果:
-20.123456
答案 2 :(得分:0)
这可以通过多种方式实现 -
1.上述过程也是适用的
2
String s =“200.0 - ”;
String[] str = s.split("-");
double data=Double.parseDouble(str[0]);
data*=-1;