Java float 123.129456到123.12没有舍入 [英] Java float 123.129456 to 123.12 without rounding

查看:182
本文介绍了Java float 123.129456到123.12没有舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将java中的 float 原语减少到两个十进制的位置,而不使用舍入?

  123.99999 to 123.99 
-8.022222 to -8.02

不应该舍入小数位,而是留下两位。第二点是如何验证或计算点后的小数点数:
$ b
$ b

  123.99会给出true或2 
123.999会给出false或3






UPDATE



这些数字是字符串输入,所以我想我会一起去建议;我只是有int try / catch块的例外。任何建议如何让这个工作更聪明的方式是欢迎:

pre $ 公共静态浮动onlyTwoDecimalPlaces(字符串数字){
StringBuilder sbFloat = new StringBuilder(number);
int start = sbFloat.indexOf(。);
if(start <0){
return new Float(sbFloat.toString());
}
int end = start + 3; ((end)>(sbFloat.length() - 1))end = sbFloat.length();

String twoPlaces = sbFloat.substring(start,end);
sbFloat.replace(start,sbFloat.length(),twoPlaces);
返回新的浮点数(sbFloat.toString());


解决方案

首先,不能保证只是因为一个float可以精确地表示 a.bcde ,它可以保证能够表示 a.bc

所以如果你只是在打印部分之后,那么用一些字符串操作呢?使用 indexOf 查找小数点,并使用 substring 。 b

How do you cut down float primitive in java to two decimal places, without using rounding?:

123.99999 to 123.99
-8.022222 to -8.02

There should be no rounding just cut of the decimal places and leave two.

Second point is how do you validate or count how many decimals are after the point?:

123.99 will give true or 2
123.999 will give false or 3


UPDATE

The numbers are String input so I think I will go with this as suggested; and I'll just have int try/catch block for any exceptions. Any suggestions how to make this work any smarter way are welcome:

public static float onlyTwoDecimalPlaces(String number) {
    StringBuilder sbFloat = new StringBuilder(number);
    int start = sbFloat.indexOf(".");
    if (start < 0) {
        return new Float(sbFloat.toString());
    }
    int end = start+3;
    if((end)>(sbFloat.length()-1)) end = sbFloat.length();

    String twoPlaces = sbFloat.substring(start, end);
    sbFloat.replace(start, sbFloat.length(), twoPlaces);
    return new Float(sbFloat.toString());
}

解决方案

First of all, there is no guarantee that just because a float can represent a.bcde exactly, it is guaranteed to be able to represent a.bc exactly.

So if you're after just the printing part, how about doing it with some string-manipulation? Find the decimal point using indexOf and extract the part with two decimals, using substring.

这篇关于Java float 123.129456到123.12没有舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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