Fomat在没有使用字符串的情况下加倍到2个小数位

时间:2015-05-11 11:48:16

标签: java double tableview

我正在处理一个项目,该项目要求我在正好2位小数处有两个值。使用一些数学,我目前有大多数数字正确舍入,除非有尾随零。我希望保留这些0以获得 0.00特别是这样的结果。此列表显示在 TableView 中,因此必须以数字方式排序。我希望双值实际上是双倍的,以便它可以正确排序。

有没有办法可以在没有String.format的情况下保留2位小数?

提前谢谢。

5 个答案:

答案 0 :(得分:2)

您可以使用DecimalFormat

DecimalFormat df = new DecimalFormat("#.00"); 

00 = 正好两位小数。

但如果你不想让这个String check this question看到double,那么你会再次转换为String-conversion BigDecimal可以使用DecimalFormat来实现。

恕我直言,如果这不是学习pourposes String就足够了。是的,您必须在转化的某个时刻使用double,但您只会阅读并存储ABAddressBook addressBook = ABAddressBookCreateWithOptions(NULL, error); CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook); CFIndex nPeople = ABAddressBookGetPersonCount(addressBook); int maxThreads = 8; int chunkSize = (int)(nPeople/maxThreads); for (int loopNum = 0; loopNum < maxThreads; loopNum++) { int initCondition = chunkSize*loopNum; int termCondition = (loopNum==(maxThreads-1)) ? (int)nPeople : chunkSize*(loopNum+1); dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ for (int i=initCondition; i<termCondition; i++) { @try { ABRecordRef person = CFArrayGetValueAtIndex(allPeople, i); NSString *firstName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty)) ? (__bridge NSString *)(ABRecordCopyValue(person, kABPersonFirstNameProperty)) : @""; NSString *lastName = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty)) ? (__bridge NSString *)(ABRecordCopyValue(person, kABPersonLastNameProperty)) :@""; NSString *birthDate = (__bridge NSString *)(ABRecordCopyValue(person, kABPersonBirthdayProperty)); ABMultiValueRef emailMultiValue = ABRecordCopyValue(person, kABPersonEmailProperty); NSArray *emailAddresses = (__bridge NSArray *)ABMultiValueCopyArrayOfAllValues(emailMultiValue); ABMultiValueRef phoneNumbers = ABRecordCopyValue(person, kABPersonPhoneProperty); NSMutableArray *numbers = [NSMutableArray arrayWithCapacity:ABMultiValueGetCount(phoneNumbers)]; for (CFIndex i = 0; i < ABMultiValueGetCount(phoneNumbers); i++) { NSString *phoneNumber = (__bridge_transfer NSString *) ABMultiValueCopyValueAtIndex(phoneNumbers, i); phoneNumber = [self removeSpecialChars:phoneNumber]; if ([phoneNumber length] >= 8) { NSString *mobileNumber = [self getPhoneNuber:phoneNumber];; if ([mobileNumber length] > 7 && [mobileNumber length] < 11) [numbers addObject:mobileNumber]; } } NSString *mobileNumbers = [numbers componentsJoinedByString:@","]; } @catch (NSException *exception) { NSLog(@"%@", exception); } } }); } ,您的排序将是正确的...... < / p>

答案 1 :(得分:1)

这个答案扩展了使用java.math.BigDecimal而不是double的建议。

这个应用程序比double更好,因为每两个小数位数在BigDecimal中是完全可表示的。从任意可双重表示的值到小数点后两位的舍入可以根据几种舍入模式中的任何一种容易地完成,包括用于双算术的舍入模式。

另一方面,它优于String,因为自然排序顺序是数值。

这是一个简短的演示程序,说明了这些要点:

mvn clean compile war:war

输出:

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Test {
  public static void main(String[] args) throws Throwable {
    List<BigDecimal> list = new ArrayList<BigDecimal>();
    double[] in = {
        3.5,
        Math.PI,
        -100.123456,
        1e6
    };
    System.out.println("Original doubles: "+Arrays.toString(in));
    for(double d : in){
      list.add(doubleToBigDecimal(d,1));
    }
    System.out.println("Before sorting: " + list);
    Collections.sort(list);
    System.out.println("After sorting: " + list);
  }

  public static BigDecimal doubleToBigDecimal(double in, int places) {
    BigDecimal result = new BigDecimal(in).setScale(2,
        BigDecimal.ROUND_HALF_EVEN);
    return result;
  }
}

答案 2 :(得分:0)

您可以使用DecimalFormat,只需将DecimalFormat的构造函数中的格式设置为您所需的2dp即可:

double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));

输出:

1.23

此代码将十进制小数向上舍入到小数位但是如果它自身的值不是最小2位小数,则它的结果将不会达到小数点后2位。 e.g。

    double d = 1.2;
    DecimalFormat df = new DecimalFormat("#.##");
    System.out.print(df.format(d));

输出:

1.2
正如Thisaru Guruge所说,Jordi Castilla回答你可以使用:

 double d = 1.2;
    DecimalFormat df = new DecimalFormat("#.00");
    System.out.print(df.format(d));

输出:

1.20

答案 3 :(得分:0)

您可以尝试BigDecimal,或者您可以创建自己的对象来实现Comparable接口进行排序,并使用toString()方法输出格式化为两位小数的值。

class TableValue implements Comparable<TableValue> {

    double value;

    public TableValue(double value) {
        this.value = value;

    }

    public int compareTo(TableValue o) {
        return Double.compare(this.value, o.value);
    }


    public String toString() {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(value);
    }
}

答案 4 :(得分:0)

双打是不精确的,BigDecimal有一个额外的属性:它的精确度。

所以new BigDecimal("5.20")的精度为2,而双5.20 * 10000的精度可能与52000.0完全不同。

注意可避免new BigDecimal(5.20)既不知道精确度,也不精确。

不幸的是,BigDecimal有COBOListic用法。