java:将浮点转换为字符串,将字符串转换为浮点
如何将浮点转换为字符串或字符串转换为浮点 在我的例子中,我需要在两个值字符串(我从表中得到的值)和我计算的浮点值之间进行断言java:将浮点转换为字符串,将字符串转换为浮点,java,string,types,number-formatting,type-conversion,Java,String,Types,Number Formatting,Type Conversion,如何将浮点转换为字符串或字符串转换为浮点 在我的例子中,我需要在两个值字符串(我从表中得到的值)和我计算的浮点值之间进行断言 String valueFromTable = "25"; Float valueCalculated =25.0; 我试着从浮动到字符串: String sSelectivityRate = String.valueOf(valueCalculated ); 但是断言使用Java的类失败了 要进行比较,最好将字符串转换为float并作为两个float进行比较。这是因
String valueFromTable = "25";
Float valueCalculated =25.0;
我试着从浮动到字符串:
String sSelectivityRate = String.valueOf(valueCalculated );
但是断言使用Java的类失败了
要进行比较,最好将字符串转换为float并作为两个float进行比较。这是因为对于一个浮点数,有多个字符串表示形式,当与字符串比较时(例如“25”!=“25.0”!=“25.00”等),这些表示形式是不同的。您可以尝试以下代码示例:
public class StringToFloat
{
public static void main (String[] args)
{
// String s = "fred"; // do this if you want an exception
String s = "100.00";
try
{
float f = Float.valueOf(s.trim()).floatValue();
System.out.println("float f = " + f);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}
}
}
找到浮点到字符串-string.valueOf() 要浮动的字符串-Float.parseFloat()
我相信以下代码将有所帮助:
float f1 = 1.23f;
String f1Str = Float.toString(f1);
float f2 = Float.parseFloat(f1Str);
这是一个可能的答案,这也将给出精确的数据,只需更改所需形式的小数点 public class TestStandAlone { /** * This method is to main * @param args void */ public static void main(String[] args) { // TODO Auto-generated method stub try { Float f1=152.32f; BigDecimal roundfinalPrice = new BigDecimal(f1.floatValue()).setScale(2,BigDecimal.ROUND_HALF_UP); System.out.println("f1 --> "+f1); String s1=roundfinalPrice.toPlainString(); System.out.println("s1 "+s1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 公共类TestStandAlone{ /** *此方法不适用于 *@param args void */ 公共静态void main(字符串[]args){ //TODO自动生成的方法存根 试一试{ 浮球f1=152.32f; BigDecimal roundfinalPrice=新的BigDecimal(f1.floatValue()).setScale(2,BigDecimal.ROUND\u HALF\u UP); System.out.println(“f1-->”+f1); 字符串s1=roundfinalPrice.toPlainString(); 系统输出打印项次(“s1”+s1); }捕获(例外e){ //TODO自动生成的捕捉块 e、 printStackTrace(); } } } 输出将是 f1 --> 152.32 s1 152.32 f1-->152.32 s1 152.32
这个方法不是一个好方法,但是很简单,不建议使用。也许我应该说这是最不有效的方法,也是最糟糕的编码实践,但是,使用起来很有趣
float val=10.0;
String str=val+"";
在空引号中,向变量str添加空字符串,向字符串类型上转换“val”。string str=“1234.56”;
String str = "1234.56";
float num = 0.0f;
int digits = str.length()- str.indexOf('.') - 1;
float factor = 1f;
for(int i=0;i<digits;i++) factor /= 10;
for(int i=str.length()-1;i>=0;i--){
if(str.charAt(i) == '.'){
factor = 1;
System.out.println("Reset, value="+num);
continue;
}
num += (str.charAt(i) - '0') * factor;
factor *= 10;
}
System.out.println(num);
float num=0.0f;
int digits=str.length()-str.indexOf('.')-1;
浮动系数=1f;
对于(int i=0;i=0;i--){
如果(str.charAt(i)='。){
系数=1;
System.out.println(“重置,value=“+num”);
继续;
}
num+=(str.charAt(i)-'0')*因子;
系数*=10;
}
系统输出打印项数(num);
如果您要查找,请输入两位小数。。
浮动f=(浮动)12.34;
字符串s=新的十进制格式(“#.00”)。格式(f);
有三种方法可以将浮点值转换为字符串。
public class Test {
public static void main(String[] args) {
System.out.println("convert FloatToString " + convertFloatToString(34.0f));
System.out.println("convert FloatToStr Using Float Method " + convertFloatToStrUsingFloatMethod(23.0f));
System.out.println("convert FloatToStr Using String Method " + convertFloatToStrUsingFloatMethod(233.0f));
float f = Float.valueOf("23.00");
}
public static String convertFloatToString(float f) {
return "" + f;
}
public static String convertFloatToStrUsingFloatMethod(float f) {
return Float.toString(f);
}
public static String convertFloatToStrUsingStringMethod(float f) {
return String.valueOf(f);
}
}
完全手动操作:此方法通过移动数字的小数点并使用下限(到长)和模来提取数字,从而将双精度转换为字符串。此外,它还使用基数除法计算小数点所属的位置。当数字到达小数点后的位置时,它还可以“删除”数字的较高部分,以避免因超大倍数而失去精度。请参阅末尾的注释代码。在我的测试中,当Java浮点表示实际显示这些不精确的小数位时,它的精确度永远不会低于Java浮点表示本身
/**
* Convert the given double to a full string representation, i.e. no scientific notation
* and always twelve digits after the decimal point.
* @param d The double to be converted
* @return A full string representation
*/
public static String fullDoubleToString(final double d) {
// treat 0 separately, it will cause problems on the below algorithm
if (d == 0) {
return "0.000000000000";
}
// find the number of digits above the decimal point
double testD = Math.abs(d);
int digitsBeforePoint = 0;
while (testD >= 1) {
// doesn't matter that this loses precision on the lower end
testD /= 10d;
++digitsBeforePoint;
}
// create the decimal digits
StringBuilder repr = new StringBuilder();
// 10^ exponent to determine divisor and current decimal place
int digitIndex = digitsBeforePoint;
double dabs = Math.abs(d);
while (digitIndex > 0) {
// Recieves digit at current power of ten (= place in decimal number)
long digit = (long)Math.floor(dabs / Math.pow(10, digitIndex-1)) % 10;
repr.append(digit);
--digitIndex;
}
// insert decimal point
if (digitIndex == 0) {
repr.append(".");
}
// remove any parts above the decimal point, they create accuracy problems
long digit = 0;
dabs -= (long)Math.floor(dabs);
// Because of inaccuracy, move to entirely new system of computing digits after decimal place.
while (digitIndex > -12) {
// Shift decimal point one step to the right
dabs *= 10d;
final var oldDigit = digit;
digit = (long)Math.floor(dabs) % 10;
repr.append(digit);
// This may avoid float inaccuracy at the very last decimal places.
// However, in practice, inaccuracy is still as high as even Java itself reports.
// dabs -= oldDigit * 10l;
--digitIndex;
}
return repr.insert(0, d < 0 ? "-" : "").toString();
}
/**
*将给定的双精度转换为完整的字符串表示形式,即不使用科学符号
*并且始终在小数点后12位。
*@param d要转换的双精度
*@返回完整的字符串表示形式
*/
公共静态字符串fullDoubleToString(最终双d){
//单独处理0,将导致以下算法出现问题
如果(d==0){
返回“0.000000000000”;
}
//查找小数点以上的位数
双重测试d=数学abs(d);
int digitsBeforePoint=0;
而(testD>=1){
//这会降低低端的精度,这无关紧要
testD/=10d;
++数字化;
}
//创建十进制数字
StringBuilder repr=新的StringBuilder();
//10^确定除数和当前小数位数的指数
int digitIndex=DigitBeforePoint;
双dabs=数学abs(d);
而(数字索引>0){
//以10的当前幂次接收数字(=小数位数)
长数字=(长)数学层(dabs/Math.pow(10,数字索引-1))%10;
报告附加(数字);
--数字索引;
}
//插入小数点
如果(数字索引==0){
报告附加(“.”);
}
//如果删除小数点以上的任何零件,则会产生精度问题
长数字=0;
dabs-=(长)数学地板(dabs);
//由于不准确,请使用小数点后的全新计算数字系统。
而(数字索引>-12){
//将小数点向右移动一步
dabs*=10d;
最终var oldDigit=数字;
数字=(长)数学地板(dabs)%10;
报告附加(数字);
//这可以避免小数点后最后一位的浮点误差。
//然而,在实践中,错误率仍然和Java本身报告的一样高。
//dabs-=旧数字*10l;
--数字索引;
}
返回repr.insert(0,d<0?-“:”).toString();
}
请注意,虽然StringBuilder用于提高速度,但此方法可以很容易地重写为使用数组,因此也可以在其他语言中使用。您知道
float
值从来都不精确吗?是否将它们作为String
或float
值进行比较?这不是一回事float
的精度低于double的精度,并且两者中的任何一个都可能存在计算值的舍入误差我尝试了您的解决方案,也尝试了goggle的解决方案,但当我做出断言时,我得到了:java.lang.AssertionError:expected:but was:Thank-帮助了我,需要帮助;)我需要这样进口吗
String str = "1234.56";
float num = 0.0f;
int digits = str.length()- str.indexOf('.') - 1;
float factor = 1f;
for(int i=0;i<digits;i++) factor /= 10;
for(int i=str.length()-1;i>=0;i--){
if(str.charAt(i) == '.'){
factor = 1;
System.out.println("Reset, value="+num);
continue;
}
num += (str.charAt(i) - '0') * factor;
factor *= 10;
}
System.out.println(num);
public class Test {
public static void main(String[] args) {
System.out.println("convert FloatToString " + convertFloatToString(34.0f));
System.out.println("convert FloatToStr Using Float Method " + convertFloatToStrUsingFloatMethod(23.0f));
System.out.println("convert FloatToStr Using String Method " + convertFloatToStrUsingFloatMethod(233.0f));
float f = Float.valueOf("23.00");
}
public static String convertFloatToString(float f) {
return "" + f;
}
public static String convertFloatToStrUsingFloatMethod(float f) {
return Float.toString(f);
}
public static String convertFloatToStrUsingStringMethod(float f) {
return String.valueOf(f);
}
}
/**
* Convert the given double to a full string representation, i.e. no scientific notation
* and always twelve digits after the decimal point.
* @param d The double to be converted
* @return A full string representation
*/
public static String fullDoubleToString(final double d) {
// treat 0 separately, it will cause problems on the below algorithm
if (d == 0) {
return "0.000000000000";
}
// find the number of digits above the decimal point
double testD = Math.abs(d);
int digitsBeforePoint = 0;
while (testD >= 1) {
// doesn't matter that this loses precision on the lower end
testD /= 10d;
++digitsBeforePoint;
}
// create the decimal digits
StringBuilder repr = new StringBuilder();
// 10^ exponent to determine divisor and current decimal place
int digitIndex = digitsBeforePoint;
double dabs = Math.abs(d);
while (digitIndex > 0) {
// Recieves digit at current power of ten (= place in decimal number)
long digit = (long)Math.floor(dabs / Math.pow(10, digitIndex-1)) % 10;
repr.append(digit);
--digitIndex;
}
// insert decimal point
if (digitIndex == 0) {
repr.append(".");
}
// remove any parts above the decimal point, they create accuracy problems
long digit = 0;
dabs -= (long)Math.floor(dabs);
// Because of inaccuracy, move to entirely new system of computing digits after decimal place.
while (digitIndex > -12) {
// Shift decimal point one step to the right
dabs *= 10d;
final var oldDigit = digit;
digit = (long)Math.floor(dabs) % 10;
repr.append(digit);
// This may avoid float inaccuracy at the very last decimal places.
// However, in practice, inaccuracy is still as high as even Java itself reports.
// dabs -= oldDigit * 10l;
--digitIndex;
}
return repr.insert(0, d < 0 ? "-" : "").toString();
}