简体   繁体   English

在Android中将Float转换为String

[英]Float to String conversion in android

i am trying simple calculation of float value but the output are not proper 我正在尝试简单地计算浮点值,但输出不正确

Log.i("100/50", Float.toString(100/50));
Log.i("100/100", Float.toString(100/100));
Log.i("100/250", Float.toString(100/250));
Log.i("1/5", Float.toString(1/5));

logcat output logcat输出

11-10 23:36:23.677: I/100/50(28562): 2.0
11-10 23:36:23.677: I/100/100(28562): 1.0
11-10 23:36:23.685: I/100/250(28562): 0.0
11-10 23:38:23.685: I/1/5(28562): 0.0

its a simple calculation of float, why its displaying such answer 它是对float的简单计算,为什么它会显示这样的答案

You need to use floats instead of ints, try Log.i("100/50", Float.toString(100f/50)); 您需要使用浮点数而不是整数,请尝试Log.i("100/50", Float.toString(100f/50)); this makes Java to use float arithmetic, otherwise it does int division then converts the result to float 这使得Java使用浮点运算,否则它将进行int除法,然后将结果转换为float

Do like this 像这样

Log.i("100/250", Float.toString(100f/250f));
Log.i("1/5", Float.toString(1f/5f));

output is 输出是

11-11 12:25:32.198: I/100/250(351): 0.4
11-11 12:25:32.208: I/1/5(351): 0.2

Float.toString takes an input floating point Float.toString采用输入浮点

public static String toString (float f)

where f is the float to convert to a string.

More information is available on Developers Website . 有关更多信息,请访问开发者网站

Use this code. 使用此代码。

Log.i("100/50", Float.toString(100/50f)); Log.i(“ 100/50”,Float.toString(100 / 50f)); Log.i("100/100", Float.toString(100/100f)); Log.i(“ 100/100”,Float.toString(100 / 100f)); Log.i("100/250", Float.toString(100/250f)); Log.i(“ 100/250”,Float.toString(100 / 250f)); Log.i("1/5", Float.toString(1/5f)); Log.i(“ 1/5”,Float.toString(1 / 5f));

Hope it will work for you. 希望它对您有用。

you are performing division of two integers. 您正在执行两个整数的除法。 so by default output will be in integer. 因此默认情况下,输出将为整数。 Instead of that try to type case the dividend into float eg (float)100/250 so the out put will be in float and you will get proper result 而不是尝试将大小写形式分配为浮点数,例如(float)100/250,这样,输出将处于浮点状态,您将获得正确的结果

eg instead of 100/250 try (float)100/250 or 100f/250 例如,而不是尝试100/250(浮动)100/250或100F / 250

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM