在java中向下舍入一个数字

时间:2017-05-18 07:13:00

标签: java

我想知道如何指示Java始终向下舍入给定的数字。

e.g:

1.08 rounds to 1
1.56 rounds to 1
1.67 rounds to 1
1.98 rounds to 2
1.89 rounds to 2

根据我将提供的自定义阈值,我希望它们四舍五入为12

有任何建议吗?

4 个答案:

答案 0 :(得分:0)

您可以使用BigDecimal,他们有一套舍入方法。

使用MathContext对象设置舍入和精度:

MathContext mc = new MathContext(2, RoundingMode.DOWN);
BigDecimal number = new BigDecimal(1.08, mc);

以下是文档https://docs.oracle.com/javase/7/docs/api/java/math/RoundingMode.html

答案 1 :(得分:0)

将类型转换为Integer以避免分数值

 int roundedNumber = (int) 1.89;

答案 2 :(得分:0)

对于四舍五入,你可以使用这样的函数:

int roundDown(double number, double decimals) {

    double result = number;

    // either it rounds it to the upmost number if it is above the threshold
    if (number - (int)number > decimals) {

        result = Math.ceil(result);
    }

    // or it just cuts of the end decimal places
    return (int)result;
}

然后你可以用它来调用它,其中YOURDECIMAL是一个代表阈值的double(高于它的圆形,低于它的圆形):

int myNumber = roundDown(YOURNUMBER, YOURDECIMAL);

答案 3 :(得分:0)

这个问题不是很清楚,有无限数量的可能解决方案,这里有两个:

browser = webdriver.Firefox()
browser.get("https://www.shareinvestor.com/my")
time.sleep(20)
lint_text_list = [link.text for link in browser.find_elements_by_xpath("//a[contains(@href, 'listedcompany.com')]") if link.text]
相关问题