如何舍弃浮点值,以便在十进制后不应包含0 [英] How to round off a float value so that it should not contain 0 after decimal

查看:140
本文介绍了如何舍弃浮点值,以便在十进制后不应包含0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果值如下所示,如何舍入浮点值:



例如:




  • 1.0 ==>然后它应该返回1

  • 2.0 ==>然后它应该返回2



,但如果值如下:




  • 1.2 ==>那么它应该返回1.2


  • 1.90 ==>然后它应该返回1.9




我试图舍弃它,也尝试不同的解决方案,但这对我来说不起作用。

解决方案

你可以创建一个这样的帮助函数

  static public void Normalize(String pattern,double value){
DecimalFormat formatter = new DecimalFormat的(图案);
String normalizedValue = formatter.format(value);
System.out.println(normalizedValue);
}

规范化(0。#####,2.40); // 2.4
规范化(0。#####,2.0); // 2

这对我有用。


How to round off a float value if the value is like:

eg:

  • 1.0 ==> then it should return 1
  • 2.0 ==> then it should return 2

but if the value is like:

  • 1.2 ==> then it should return 1.2

  • 1.90 ==>then it should return 1.9

I have tried to round off it and also tries different solutions but that doesn't worked for me.

解决方案

You can create a helper function like this

 static public void Normalize(String pattern, double value ) {
    DecimalFormat formatter = new DecimalFormat(pattern);
    String normalizedValue = formatter.format(value);
    System.out.println(normalizedValue);
    }

Normalize("0.#####",2.40); // 2.4
Normalize("0.#####",2.0); // 2

This worked for me.

这篇关于如何舍弃浮点值,以便在十进制后不应包含0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆