tmf.common: Add a data size and speed formatter
[deliverable/tracecompass.git] / common / org.eclipse.tracecompass.common.core / src / org / eclipse / tracecompass / common / core / format / DataSizeWithUnitFormat.java
1 /*******************************************************************************
2 * Copyright (c) 2016 Ericsson
3 *
4 * All rights reserved. This program and the accompanying materials are
5 * made available under the terms of the Eclipse Public License v1.0 which
6 * accompanies this distribution, and is available at
7 * http://www.eclipse.org/legal/epl-v10.html
8 *******************************************************************************/
9
10 package org.eclipse.tracecompass.common.core.format;
11
12 import java.text.DecimalFormat;
13 import java.text.FieldPosition;
14 import java.text.Format;
15 import java.text.ParsePosition;
16
17 /**
18 * Provides a formatter for data sizes along with the unit of size (KG, MB, GB
19 * ou TB). It receives a size in bytes and it formats a number in the closest
20 * thousand's unit, with at most 3 decimals.
21 *
22 * @author Matthew Khouzam
23 * @since 2.0
24 */
25 public class DataSizeWithUnitFormat extends Format {
26
27 private static final long serialVersionUID = 3934127385682676804L;
28 private static final String B = "B"; //$NON-NLS-1$
29 private static final String KB = "KB"; //$NON-NLS-1$
30 private static final String MB = "MB"; //$NON-NLS-1$
31 private static final String GB = "GB"; //$NON-NLS-1$
32 private static final String TB = "TB"; //$NON-NLS-1$
33 private static final long KILO = 1024;
34 private static final Format FORMAT = new DecimalFormat("#.###"); //$NON-NLS-1$
35
36 @Override
37 public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) {
38 if (obj instanceof Number) {
39 Number num = (Number) obj;
40 double value = num.doubleValue();
41 double abs = Math.abs(value);
42 if (value == 0) {
43 return toAppendTo.append("0"); //$NON-NLS-1$
44 }
45 if (abs > KILO * KILO * KILO * KILO) {
46 return toAppendTo.append(FORMAT.format(value / (KILO * KILO * KILO * KILO))).append(' ').append(TB);
47 }
48 if (abs > KILO * KILO * KILO) {
49 return toAppendTo.append(FORMAT.format(value / (KILO * KILO * KILO))).append(' ').append(GB);
50 }
51 if (abs > KILO * KILO) {
52 return toAppendTo.append(FORMAT.format(value / (KILO * KILO))).append(' ').append(MB);
53 }
54 if (abs > KILO) {
55 return toAppendTo.append(FORMAT.format(value / (KILO))).append(' ').append(KB);
56 }
57 return toAppendTo.append(FORMAT.format(value)).append(' ').append(B);
58 }
59 return toAppendTo;
60 }
61
62 @Override
63 public Object parseObject(String source, ParsePosition pos) {
64 return source == null ? "" : source; //$NON-NLS-1$
65 }
66 }
This page took 0.033347 seconds and 5 git commands to generate.