简体   繁体   English

如何在Java中删除小数部分的“ 0”?

[英]How to remove the “0,” in a fraction in Java?

I have a float value of a current weight like eg "79.3" kilograms. 我有当前重量的浮点值,例如“ 79.3”千克。 I split the float value into a kilogram and a grams value. 我将浮点值分为公斤和克值。

I get the right amount of kilograms when parsing the float-value to int. 将浮点值解析为int时,我得到的公斤数正确。 Then I get the fractional part of the float-value. 然后我得到浮点数的小数部分。 This fractional part looks like "0,3" which means 0.3 kilograms or 300grams. 该小数部分看起来像“ 0,3”,表示0.3千克或300克。 In my Programm I can only have 0,100,200,..,900 Grams which would stand for 0-9. 在我的程序中,我只能有0,100,200,..,900克,代表0-9。 My goal is to remove the "0," so I only get the value of "3". 我的目标是删除“ 0”,所以我只得到“ 3”的值。

This is my code for now and I tried some decimal formatting too, but I didn't know how to do it: 这是我现在的代码,我也尝试了一些十进制格式,但是我不知道该怎么做:

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()

Given a string 给定一个字符串

String gram = "0,3";

you can just do: 您可以这样做:

gram = gram.substring(gram.lastIndexOf(",") + 1);

which gives the following output when printed 打印时给出以下输出

3 3

I view this primarily as a math, not a Java, problem. 我主要将此视为数学问题,而不是Java问题。 Given a float input in units of kilograms, to obtain only the kilogram component, we can take the floor. 给定以千克为单位的浮点输入,仅要获取千克分量,我们就可以发言。 To get the grams component, we can multiply by 1000 and then take the mod of 1000. 要获得克分量,我们可以乘以1000,然后取1000的mod。

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

Note: I am using double here instead of float , only because Math.floor returns double as its return value. 注意:我在这里使用double而不是float ,只是因为Math.floor返回double作为其返回值。

Or you can simply do that. 或者您可以简单地做到这一点。 No need for strings. 不需要字符串。

float f = 3.3f;
int g = (int)f;
int h = Math.round((f - g)*10);

and since h is supposed to be grams, you might as well make it *1000 并且因为h应该是克,所以最好将其设为* 1000

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

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