我有当前重量的浮点值,例如“ 79.3”千克。 我将浮点值分为公斤和克值。
将浮点值解析为int时,我得到的公斤数正确。 然后我得到浮点数的小数部分。该小数部分看起来像“ 0,3”,表示0.3千克或300克。 在我的程序中,我只能有0,100,200,..,900克,代表0-9。 我的目标是删除“ 0”,所以我只得到“ 3”的值。
这是我现在的代码,我也尝试了一些十进制格式,但是我不知道该怎么做:
public void setCurrentWeightInTheNumberPickers() {
float currentWeightAsFloat = weight_dbHandler.getCurrentWeightFloat();
int currentWeightKilograms = (int) currentWeightAsFloat;
double fractionOfGrams = currentWeightAsFloat % 1;
DecimalFormat df1 = new DecimalFormat("0.##");
String rounded = df1.format(fractionOfGrams);
rounded.replaceFirst("^0+(?!$)", "");
} //public void setCurrentWeightInTheNumberPickers()
答案 0 :(得分:2)
给出一个字符串
String gram = "0,3";
您可以这样做:
gram = gram.substring(gram.lastIndexOf(",") + 1);
在打印时提供以下输出
3
答案 1 :(得分:1)
我主要将此视为数学问题,而不是Java问题。给定以千克为单位的浮点输入,仅要获取千克分量,我们就可以发言。要获得克分量,我们可以乘以1000,然后取1000的模。
double input = 79.321;
double kg = Math.floor(input);
System.out.println("kilograms: " + kg);
double g = Math.floor((1000*input) % 1000);
System.out.println("grams: " + g);
kilograms: 79.0
grams: 321.0
注意:我在这里使用double
而不是float
,只是因为Math.floor
返回了double
作为返回值。
答案 2 :(得分:1)
或者您可以简单地做到这一点。不需要字符串。
float f = 3.3f;
int g = (int)f;
int h = Math.round((f - g)*10);
并且由于h应该是g,所以您最好将其设置为* 1000