From 95fa0e517da46d3b47d77eb12bf7a3a171371dbe Mon Sep 17 00:00:00 2001 From: mdb Date: Mon, 2 Jun 2003 23:48:33 +0000 Subject: [PATCH] Added convenience methods for formatting floating point values with sensible default rules (ie. 1.45). git-svn-id: https://samskivert.googlecode.com/svn/trunk@1143 6335cc39-0255-0410-8fd6-9bcaacd3b74c --- .../java/com/samskivert/util/StringUtil.java | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/projects/samskivert/src/java/com/samskivert/util/StringUtil.java b/projects/samskivert/src/java/com/samskivert/util/StringUtil.java index d172581c..d7eac049 100644 --- a/projects/samskivert/src/java/com/samskivert/util/StringUtil.java +++ b/projects/samskivert/src/java/com/samskivert/util/StringUtil.java @@ -1,5 +1,5 @@ // -// $Id: StringUtil.java,v 1.55 2003/02/05 00:20:35 mdb Exp $ +// $Id: StringUtil.java,v 1.56 2003/06/02 23:48:33 mdb Exp $ // // samskivert library - useful routines for java programs // Copyright (C) 2001 Michael Bayne @@ -28,6 +28,8 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; +import java.text.NumberFormat; + import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; @@ -142,6 +144,28 @@ public class StringUtil return false; } + /** + * Formats a floating point value with useful default rules; + * ie. always display a digit to the left of the decimal and display + * only two digits to the right of the decimal (rounding as + * necessary). + */ + public static String format (float value) + { + return _ffmt.format(value); + } + + /** + * Formats a floating point value with useful default rules; + * ie. always display a digit to the left of the decimal and display + * only two digits to the right of the decimal (rounding as + * necessary). + */ + public static String format (double value) + { + return _ffmt.format(value); + } + /** * Converts the supplied object to a string. Normally this is * accomplished via the object's built in toString() @@ -1010,4 +1034,12 @@ public class StringUtil } private final static String XLATE = "0123456789abcdef"; + + /** Used to easily format floats with sensible defaults. */ + protected static final NumberFormat _ffmt = NumberFormat.getInstance(); + static { + _ffmt.setMinimumIntegerDigits(1); + _ffmt.setMinimumFractionDigits(1); + _ffmt.setMaximumFractionDigits(2); + } }