Java 如何除以得到十进制值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/665018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:37:38  来源:igfitidea点击:

How do I divide so I get a decimal value?

javamathdivisionmodulus

提问by

I want to know how to get remainder and quotient in single value in Java.

我想知道如何在 Java 中获得单值的余数和商数。

Example:

例子:

3/2 I should get value as 1.5.

3/2 我应该得到 1.5 的价值。

If I use the /operator I get only the quotient. If I user the %operator I get only the remainder. How do I get both at a time in the same variable?

如果我使用/运算符,我只会得到商。如果我使用%运营商,我只会得到剩余部分。如何在同一个变量中同时获得两者?

回答by vladr

In your example, Java is performing integerarithmetic, rounding off the result of the division.

在您的示例中,Java 正在执行整数算术,四舍五入除法结果。

Based on your question, you would like to perform floating-point arithmetic. To do so, at least one of your terms must be specified as (or converted to) floating-point:

根据您的问题,您想执行浮点运算。为此,必须至少将您的一项指定为(或转换为)浮点数:

Specifying floating point:

指定浮点数:

3.0/2
3.0/2.0
3/2.0

Converting to floating point:

转换为浮点数:

int a = 2;
int b = 3;
float q = ((float)a)/b;

or

或者

double q = ((double)a)/b;

(See Java Traps: doubleand Java Floating-Point Number Intricaciesfor discussions on floatand double)

(参见Java的陷阱:双Java的浮点数余光中对讨论floatdouble

回答by recursive

quotient = 3 / 2;
remainder = 3 % 2;

// now you have them both

回答by Neil Coffey

Don't worry about it. In your code, just do the separate / and % operations as you mention, even though it might seem like it's inefficient. Let the JIT compiler worryabout combining these operations to get both quotient and remainder in a single machine instruction (as far as I recall, it generally does).

别担心。在您的代码中,只需执行您提到的单独 / 和 % 操作,即使它看起来效率低下。让 JIT 编译器担心组合这些操作以在单个机器指令中获得商和余数(据我所知,它通常是这样)。

回答by Cladius Fernando

Check this out: http://download.oracle.com/javase/1,5.0/docs/api/java/math/BigDecimal.html#divideAndRemainder%28java.math.BigDecimal%29

看看这个:http: //download.oracle.com/javase/1,5.0/docs/api/java/math/BigDecimal.html#divideAndRemainder%28java.math.BigDecimal%29

You just need to wrap your intor longvariable in a BigDecimalobject, then invoke the divideAndRemaindermethod on it. The returned array will contain the quotient and the remainder (in that order).

您只需要将intlong变量包装在BigDecimal对象中,然后在其上调用divideAndRemainder方法。返回的数组将包含商和余数(按该顺序)。

回答by user3559041

If you initialize both the parameters as float, you will sure get actual divided value. For example:

如果您将两个参数都初始化为float,您肯定会得到实际的除法值。例如:

float RoomWidth, TileWidth, NumTiles;
RoomWidth = 142;
TileWidth = 8;
NumTiles = RoomWidth/TileWidth;

Ans:17.75.

答:17.75。

回答by Matthew

int a = 3;
int b = 2;
float c = ((float)a)/b

回答by Hesam

@recursive's solusion (The accepted answer) is 100% right. I am just adding a sample code for your reference.

@recursive 的解决方案(接受的答案)是 100% 正确的。我只是添加一个示例代码供您参考。

My case is to display price with two decimal digits.This is part of back-end response: "price": 2300, "currencySymbol": "CD", ....

我的情况是用两位小数显示价格。这是后端响应的一部分:"price": 2300, "currencySymbol": "CD", ...

This is my helper class:

这是我的助手类:

public class CurrencyUtils
{
    private static final String[] suffix = { "", "K", "M" };

    public static String getCompactStringForDisplay(final int amount)
    {
        int suffixIndex;
        if (amount >= 1_000_000) {
            suffixIndex = 2;
        } else if (amount >= 1_000) {
            suffixIndex = 1;
        } else {
            suffixIndex = 0;
        }

        int quotient;
        int remainder;
        if (amount >= 1_000_000) {
            quotient = amount / 1_000_000;
            remainder = amount % 1_000_000;
        } else if (amount >= 1_000) {
            quotient = amount / 1_000;
            remainder = amount % 1_000;
        } else {
            return String.valueOf(amount);
        }

        if (remainder == 0) {
            return String.valueOf(quotient) + suffix[suffixIndex];
        }

        // Keep two most significant digits
        if (remainder >= 10_000) {
            remainder /= 10_000;
        } else if (remainder >= 1_000) {
            remainder /= 1_000;
        } else if (remainder >= 100) {
            remainder /= 10;
        }

        return String.valueOf(quotient) + '.' + String.valueOf(remainder) + suffix[suffixIndex];
    }
}

This is my test class (based on Junit 4):

这是我的测试类(基于 Junit 4):

public class CurrencyUtilsTest {

    @Test
    public void getCompactStringForDisplay() throws Exception {
        int[] numbers = {0, 5, 999, 1_000, 5_821, 10_500, 101_800, 2_000_000, 7_800_000, 92_150_000, 123_200_000, 9_999_999};
        String[] expected = {"0", "5", "999", "1K", "5.82K", "10.50K", "101.80K", "2M", "7.80M", "92.15M", "123.20M", "9.99M"};

        for (int i = 0; i < numbers.length; i++) {
            int n = numbers[i];
            String formatted = CurrencyUtils.getCompactStringForDisplay(n);
            System.out.println(n + " => " + formatted);

            assertEquals(expected[i], formatted);
        }
    }

}

回答by prateek Kanujiya

Please Convert your input in double and divide.

请将您的输入转换为双倍和除法。

回答by Adan Vivero

I mean it's quite simple. Set it as a double. So lets say

我的意思是这很简单。将其设置为双。所以让我们说

double answer = 3.0/2.0;
System.out.print(answer);

回答by Mohammad Zulfikar

You can do like,

你可以这样做,

int a = 3;
int b = 2;
int quotient = a / b;
int remainder = a % b;

To get quotient in real numbers

求实数商

System.out.println((double) a / b);

To get quotient in integer numbers

得到整数的商

System.out.println("Quotient: " + quotient);
System.out.println("Remainder: " + remainder);

To get quotient in real number such that one number after decimal

求实数中的商,使小数点后一位数

System.out.println(a / b + "." + a % b * 10 / b);

Note: In the last method it will not round the number up after the decimal.

注意:在最后一种方法中,它不会将小数点后的数字四舍五入。