java: Konwertuj float na String i String na float
Jak mogę przekonwertować z float na string lub string na float?
W moim przypadku muszę wykonać twierdzenie pomiędzy 2 wartościami string (wartość, którą otrzymałem z tabeli) a wartością float, którą obliczyłem.
String valueFromTable = "25";
Float valueCalculated =25.0;
Próbowałem od float do string:
String sSelectivityRate = String.valueOf(valueCalculated );
Ale twierdzenie zawodzi
10 answers
Używanie Javy Float
klasy.
float f = Float.parseFloat("25");
String s = Float.toString(25.0f);
Aby porównać, zawsze lepiej jest przekonwertować łańcuch na float i porównać go jako dwa Floaty. Dzieje się tak, ponieważ dla jednej liczby zmiennoprzecinkowej istnieje wiele reprezentacji łańcuchów, które różnią się w porównaniu z łańcuchami (np. "25" != "25.0" != "25.00" itd.)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-28 23:46:37
Float to string-String.valueOf ()
float amount=100.00f;
String strAmount=String.valueOf(amount);
// or Float.toString(float)
String to Float-Float.parseFloat ()
String strAmount="100.20";
float amount=Float.parseFloat(strAmount)
// or Float.valueOf(string)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-26 08:53:56
Możesz wypróbować ten przykład kodu:
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());
}
}
}
Znaleziono tutaj
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-26 08:47:21
Wierzę, że poniższy kod pomoże:
float f1 = 1.23f;
String f1Str = Float.toString(f1);
float f2 = Float.parseFloat(f1Str);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-09-26 08:48:31
Jest to możliwa odpowiedź, to również poda dokładne dane, wystarczy zmienić punkt dziesiętny w wymaganej formie.
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(); } } }
Wyjście będzie
f1 --> 152.32 s1 152.32
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-20 11:06:09
Jeśli szukasz, powiedz dwa miejsca po przecinku..
Float f = (float)12.34;
String s = new DecimalFormat ("#.00").format (f);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-05-30 13:03:54
Cóż ta metoda nie jest dobra, ale łatwa i nie sugerowana. Może powinienem powiedzieć, że jest to najmniej skuteczna metoda i gorsza praktyka kodowania, ale, zabawa w użyciu,
float val=10.0;
String str=val+"";
Puste cudzysłowy, dodać null string do zmiennej str, upcasting 'val' Do typu string.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-24 18:41:43
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);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-12 04:34:24
Istnieją trzy sposoby konwersji float na String.
- "" + f
- Float.toString (f)
- String.valueOf (f)
Istnieją dwa sposoby konwersji String na float
- Float.valueOf (str)
- Float.parseFloat (str);
Przykład:-
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);
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-02-14 09:43:45
Aby przejść pełną trasę ręczną: ta metoda konwertuje podwaja na ciągi znaków, przesuwając punkt dziesiętny liczby wokół i używając podłogi (na long) i modułu do wyodrębniania cyfr. Ponadto używa liczenia przez podział bazy, aby ustalić miejsce, w którym należy punkt dziesiętny. Może również "usunąć" wyższe części liczby po osiągnięciu miejsc po przecinku, aby uniknąć utraty precyzji przy ultra-dużych podwójnych. Zobacz skomentowany kod na końcu. W moich testach nigdy nie jest mniej dokładna niż same reprezentacje float Javy, kiedy faktycznie pokazują te nieprecyzyjne dolne miejsca po przecinku.
/**
* 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();
}
Zauważ, że podczas gdy StringBuilder jest używany dla szybkości, ta metoda może być łatwo przepisana do użycia tablic i dlatego działa również w innych językach.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-10-07 21:26:28