/* * [DecimalBase.java] * * Summary: common Base class for classes that convert numbers to formatted decimal. * * Copyright: (c) 1999-2017 Roedy Green, Canadian Mind Products, http://mindprod.com * * Licence: This software may be copied and used freely for any purpose but military. * http://mindprod.com/contact/nonmil.html * * Requires: JDK 1.8+ * * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/ * * Version History: * 1.0 1999-01-17 * 1.1 2005-08-26 correct bug in 9-digit negative numbers * split off common logic from DecimalCommas and DecimalDots */ package com.mindprod.inwords; /** * common Base class for classes that convert numbers to formatted decimal. *

* com.mindprod.inwords.DecimalBase.java - convert long integer * into formatted Decimal e.g. * -12345 -> -12.345, uses variable separater e.g. space dot * comma. *

* * @author Roedy Green, Canadian Mind Products * @version 1.1 2005-08-26 correct bug in 9-digit negative numbers * split off common logic from DecimalCommas and DecimalDots * @ split off common logic from DecimalCommas and DecimalDots * @noinspection WeakerAccess * @since 1999-01-17 */ public class DecimalBase { private static final int FIRST_COPYRIGHT_YEAR = 1999; /** * undisplayed copyright notice * * @noinspection UnusedDeclaration */ private static final String EMBEDDED_COPYRIGHT = "Copyright: (c) 1999-2017 Roedy Green, Canadian Mind Products, http://mindprod.com"; /** * convert long integer into tidied Decimal e.g. -12345 -> -12.345 Handles negative and positive integers on range * -Long.MIN_VALUE .. Long.MAX_VALUE; * * @param num number to convert to words * @param sep separarator comma, period, space. * * @return words */ public String toWords( long num, char sep ) { boolean negative; if ( num < 0 ) { negative = true; num = -num; } else { negative = false; } String s = Long.toString( num ); // insert decorative dots every three int length = s.length(); // count of separators we will insert int sepsCount = ( length - 1 ) / 3; if ( sepsCount > 0 ) { StringBuilder b = new StringBuilder( length + sepsCount ); // work left to right. // where we will insert first dot. int sepSpot = ( ( length - 1 ) % 3 ) + 1; b.append( s.substring( 0, sepSpot ) ); for ( int group = 0; group < sepsCount; group++, sepSpot += 3 ) { b.append( sep ); b.append( s.substring( sepSpot, sepSpot + 3 ) ); } // end for s = b.toString(); } // end if return negative ? '-' + s : s; } // end toWords } // end DecimalBase