本文介绍了如何从Java中包含.0的浮点数中删除小数部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想删除包含 .0 的浮点数的小数部分.所有其他数字都是可以接受的.例如:

I just want to remove the fractional part of a float number that contains .0. All other numbers are acceptable..For example :

  I/P: 1.0, 2.2, 88.0, 3.56666, 4.1, 45.00 , 99.560
  O/P: 1 ,  2.2, 88,   3.567,   4.1, 45 ,    99.560

除了"将数字与".0"进行比较并采用子字符串"之外,是否有其他方法可以实现?

Is there any method available to do that other than "comparing number with ".0" and taking substring" ?

我不想要浮动数字(例如1.0、2.0就是1 2对不对?)

EDIT : I don't want ACTING FLOAT NUMBERs (like 1.0, 2.0 is nothing but 1 2 right?)

我觉得我的问题有点令人困惑...
这是我的澄清:我只想向用户显示一系列浮点数.如果数字的小数部分为零,则仅显示整数部分,否则按原样显示数字.我希望现在已经清楚了.

I feel my question is little confusing...
Here is my clarification: I just want to display a series of floating point numbers to the user. If the fractional part of a number is zero, then display only the integer part, otherwise display the number as it is. I hope it's clear now..

推荐答案

您可以使用正则表达式,例如: \\.0 + $ .如果小数点后只有0,则此正则表达式将为true.

You could use a regular expression such as this: \\.0+$. If there are only 0's after the decimal point this regular expression will yield true.

您可以做的另一件事是这样的:

Another thing you could do is something like so:

float x = 12.5;
float result = x - (int)x;
if (result != 0)
{
    //If the value of `result` is not equal to zero, then, you have a decimal portion which is not equal to 0.
}

这篇关于如何从Java中包含.0的浮点数中删除小数部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-14 20:38