将浮点数转换为整数的方法,在检查后进行转换

huangapple go评论71阅读模式
英文:

Method for converting float to integer after checking

问题

我正在尝试对两个数字(称为A和B)执行多个操作。这两个数字通过单个字符串输入。所以我将它们转换为Double值并对它们执行操作。

问题在于输出始终是double。如果结果是整数,我希望答案是整数答案,例如2而不是2.0

情况:

  1. A= 2B= 2(输入为字符串)=> 提取为浮点变量 => varA= 2.0,varB=2.0 当前结果 => 4.0(简单的*操作)最佳结果 => 4

  2. A= 2.0B= 2.0(输入为字符串)=> 提取为浮点变量 => varA= 2.0,varB=2.0 当前结果 => 4.0(简单的*操作)最佳结果 => 4.0

我查了一下,没有太大帮助。因为这些问题通常涉及到转换或精度。如果有类似或有帮助的问题的链接,我可能错过了也可以。我知道如何从float转换为int,但我正在寻找检查数字是否可以表示为整数的最佳方法。然后根据情况获取结果。

谢谢。

英文:

I am trying to perform multiple operations on two numbers (say A and B). These two numbers are getting inputted via a single string. So I am converting them into Double values and performing an operation on them.

The poblem is that the output is always double. I would like to have the answer to be an integer answer if the result is an integer, say, 2 instead of 2.0.

Cases:

  1. A= 2 and B= 2 (input in string )=> extracted into float variables => varA= 2.0, varB=2.0 current result => 4.0 (simple * operation ) optimum result => 4

  2. A= 2.0 and B= 2.0 (input in string )=> extracted into float variables => varA= 2.0, varB=2.0 current result => 4.0 (simple * operation ) optimum result => 4.0

I looked it up and it wasn't much help. As such questions either deal with conversion or precision. Links to any similar/helping questions that I might have missed will work too. I know how to convert from float to int, but looking for optimum way to check if a number can be represented in int or not. And get result accordingly.

Thank you

答案1

得分: 1

你可以尝试使用%运算符来判断这两个双精度数是否产生了一个完美的除法,并像下面这样使用整数转换。

    double num1 = 20.0;
    double num2 = 5.0;
        
    if (num1num2 == 0) {
        System.out.println((long) (num1/num2));
    } else {
        System.out.println(num1/num2);
    }
英文:

You can try and use % operator to decide if the two doubles produce a perfect division and use integer casting like below.

double num1 = 20.0;
double num2 = 5.0;
    
if (num1%num2 == 0) {
    System.out.println((long) (num1/num2));
} else {
    System.out.println(num1/num2);
}

huangapple
  • 本文由 发表于 2020年9月28日 18:49:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64100729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定