KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tc > util > stringification > PrettyPrintUtils


1 /**
2  * All content copyright (c) 2003-2006 Terracotta, Inc., except as may otherwise be noted in a separate copyright notice. All rights reserved.
3  */

4 package com.tc.util.stringification;
5
6 import com.tc.util.Assert;
7
8 /**
9  * Contains methods for pretty-printing various things.
10  */

11 public class PrettyPrintUtils {
12
13   public static String JavaDoc pluralize(String JavaDoc base, int quantity) {
14     if (quantity == 1) return base;
15     else if (base.trim().toLowerCase().endsWith("s")) return base + "es";
16     else return base + "s";
17   }
18
19   public static String JavaDoc quantity(String JavaDoc ofWhat, int howMany) {
20     return "" + howMany + " " + pluralize(ofWhat, howMany);
21   }
22
23   public static String JavaDoc percentage(double value, int howManyDecimalDigits) {
24     Assert.eval(howManyDecimalDigits >= 0);
25
26     value *= 100.0;
27
28     int integral = howManyDecimalDigits > 0 ? (int) value : (int) Math.round(value);
29     int fraction = (int) Math.round(Math.abs(value - integral) * 100.0);
30
31     String JavaDoc integralPart = Integer.toString(integral);
32     String JavaDoc fractionPart = Integer.toString(fraction);
33     while (fractionPart.length() < howManyDecimalDigits)
34       fractionPart = "0" + fractionPart;
35
36     if (howManyDecimalDigits == 0) return integralPart + "%";
37     else return integralPart + "." + fractionPart + "%";
38   }
39
40 }
41
Popular Tags