convert a String to a float with Java
convert a String to a float with Java
An example of a simple program that performs this conversion is shown below:
كود:
public class s2f {
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());
}
}
}
Other notes
كود:
Float.toString(float f)
is used to convert in the other direction, from a float to a String.
رد: convert a String to a float with Java
فى السطر 1 الكود ده بيعمل ايه ؟
كود:
1-s.trim()
2-float f = Float.valueOf(s);
ولو كنت كتبت السطر التانى كانت هتتنفذ عادى صح ؟؟؟
رد: convert a String to a float with Java
اقتباس:
المشاركة الأصلية كتبت بواسطة abacy
فى السطر 1 الكود ده بيعمل ايه ؟
كود:
1-s.trim()
2-float f = Float.valueOf(s);
ولو كنت كتبت السطر التانى كانت هتتنفذ عادى صح ؟؟؟
بتمسح أى مسافات قبل وبعد السترنج
مثلا
" Ahmed Baraka "
بترجع السترنج
"Ahmed Baraka"
-- بصراحة مش جربت السطر التانى على طول ممكن تجربها وتقولنا أشتغلت ولا لأ
بس أعتقد أنها هتشتغل بس فى بعض الحالات ممكن تعمل أكسبشن ومش تشتغل
رد: convert a String to a float with Java
شكرا :)
ايوة هى اشتغلت معايا بحس انهم بيعمله نفس الحل
وتقريبا مش بحس بفرق بين الاتنين دول كمان
كود:
Float.parseFloat(s);
Float.value(s);