0

I have declared two float variables for addition purpose...

So, the user can input 2.2+2.2 and get 4.4 And sometimes the user will enter 2+2 and will get 4.0>> this zero needs to be deleted.

I can't use the round method nor converting the whole result into an integer.

My Actual code is here:

holder.txtTotalViews.setText(new StringBuilder().append(new java.text.DecimalFormat("#").format(Float.parseFloat(trendingVideoList.get(position).getTotal_views())/1000)).append("K ").append(activity.getString(R.string.lbl_views)));

I need to calculate total views of video into K format like 10K and 10.5K. I have problem to remove zero from 10.0K.

Paras Santoki
  • 821
  • 11
  • 26
  • 2
    use `DecimalFormat("#.#").format(solution)` – Jyoti JK Apr 17 '18 at 10:16
  • Possible duplicate of [How to nicely format floating numbers to String without unnecessary decimal 0?](https://stackoverflow.com/questions/703396/how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0) – xyz Apr 17 '18 at 11:14
  • This question does not solve my problem. I need to calculate total views of video into K format like 10K and 10.5K. I have problem to remove zero from 10.0K. – Paras Santoki Apr 17 '18 at 11:23

2 Answers2

1

My Issue is resolved by changing decimal format of the code: Thanks to @Jyoti now my code:

I need to change my new java.text.DecimalFormat("#") to new java.text.DecimalFormat("#.#") like this.

holder.txtTotalViews.setText(new StringBuilder().append(new java.text.DecimalFormat("#.#").format(Float.parseFloat(trendingVideoList.get(position).getTotal_views())/1000)).append("K ").append(activity.getString(R.string.lbl_views)));
Jyoti JK
  • 2,141
  • 1
  • 17
  • 40
Paras Santoki
  • 821
  • 11
  • 26
1

You can make a common function like this:

// No need to re-create decimal format instance. Keep this outside of the function.
DecimalFormat decimalFormat = new DecimalFormat("#.#");
public String numberToString(float number){
    if(number == (int) number){
        return Integer.toString((int) number);
    }
    return decimalFormat.format(number);
}
Metehan Toksoy
  • 1,885
  • 3
  • 22
  • 39