001/******************************************************************************* 002 * This software is provided as a supplement to the authors' textbooks on digital 003 * image processing published by Springer-Verlag in various languages and editions. 004 * Permission to use and distribute this software is granted under the BSD 2-Clause 005 * "Simplified" License (see http://opensource.org/licenses/BSD-2-Clause). 006 * Copyright (c) 2006-2023 Wilhelm Burger, Mark J. Burge. All rights reserved. 007 * Visit https://imagingbook.com for additional details. 008 ******************************************************************************/ 009package imagingbook.common.math; 010 011/** 012 * This class holds settings to control the precision when printing floating-point numbers, used in particular by 013 * various {@code toString()} methods for vectors and matrices defined in class {@link Matrix} (mainly for debugging). 014 * 015 * @author WB 016 */ 017public abstract class PrintPrecision { 018 019 private PrintPrecision() {} 020 021 /** The default precision (number of digits = 3). */ 022 public static final int DefaultPrecision = 3; 023 024 private static int precision = DefaultPrecision; 025 private static String formatString; 026 027 static { 028 reset(); // to properly set the formatString 029 } 030 031 /** 032 * Reset print precision to the default value 033 * ({@link #DefaultPrecision}). 034 */ 035 public static void reset() { 036 set(DefaultPrecision); 037 } 038 039 /** 040 * Set print precision to the specified number of digits. For example, with {@code nDigits = 5} the resulting 041 * element format string is {@code "%.5f"}. If a value ≤0 is specified, the scientific float format string 042 * {@code "%e"} is used. 043 * 044 * @param nDigits the number of digits to be used 045 */ 046 public static void set(int nDigits) { 047 precision = Math.max(nDigits, 0); 048 if (nDigits > 0) { 049 formatString = "%." + precision + "f"; // e.g. "%.5f" 050 } 051 else { 052 formatString = "%e"; // use scientific format - OK? 053 } 054 } 055 056 /** 057 * Returns the current print precision (number of digits). 058 * @return the current number of digits 059 */ 060 public static int get() { 061 return precision; 062 } 063 064 /** 065 * Returns the floaing-point format string for the current print precision (to be used in 066 * {@link String#format(String, Object...)}, for example {@code "%.6f"} if print precision is set to 6, or 067 * {@code "%e"} when precision ≤0. 068 * 069 * @return the format string 070 */ 071 public static String getFormatStringFloat() { 072 return formatString; 073 } 074}