如何将带有1个小数点的浮点值存储为java中的浮点值。对于(例如),我使用以下代码将浮点值限制为小数点后的1位但作为字符串,因此再次将其转换为浮点数。但是,在转换接收到像(值= 2.39725527E11)这样的长浮点值后,我需要它(如果值= 2.3)并将其存储在浮点变量中,而不是2.39725527E11
float_str = String.format("%.1f", value);
value = Float.parseFloat(float_str);
System.out.println("value = " + value);
答案 0 :(得分:3)
您可以使用BigDecimal
。像,
BigDecimal bd = BigDecimal.valueOf(2.39725527E11f);
bd = bd.setScale(1, RoundingMode.HALF_UP);
System.out.println("value = " + bd);
我得到了
value = 239725527040.0
或者,删除指数然后舍入可以为您提供类似
的内容float f = 2.39725527E11f;
f /= Math.pow(10, (int) Math.log10(f));
f = ((int) (f * 10)) / 10.0f; // <-- performs one digit floor
System.out.println("value = " + f);
我得到了
value = 2.3
答案 1 :(得分:0)
如果您已将浮动字符串作为字符串,我相信这会起作用......
String floatstr = ""; // Create a variable to assign string values too
for (int i = 0; i < float_str.length(); i++) // Loop through the character array in the string.
floatstr += float_str.charAt(i); // add the current value to floatstr
if (float_str.charAt(i) == '.' && i != float_str.length() - 1) // If there is a dot, and it isn't the last character
{
floatstr += float_str.charAt(i + 1); // add the next character to it
break; // break so it doesn't take in any more characters
}
float_str = floatstr; // Assign the string with one variable next to dot back into original string.