Java String Chop chopToNSignificantDigits(final float original, int no_of_sig_digits)

Here you can find the source of chopToNSignificantDigits(final float original, int no_of_sig_digits)

Description

chop To N Significant Digits

License

Open Source License

Declaration

public static final float chopToNSignificantDigits(final float original, int no_of_sig_digits) 

Method Source Code

//package com.java2s;
/* //from www  . java 2s.com
  This file is part of JIV.  
  Copyright (C) 2000, 2001 Chris A. Cocosco (crisco@bic.mni.mcgill.ca)
    
  JIV is free software; you can redistribute it and/or modify it under
  the terms of the GNU General Public License as published by the Free
  Software Foundation; either version 2 of the License, or (at your
  option) any later version.
    
  JIV is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
  License for more details.
    
  You should have received a copy of the GNU General Public License
  along with JIV; if not, write to the Free Software Foundation, Inc.,
  59 Temple Place, Suite 330, Boston, MA 02111-1307 USA, 
  or see http://www.gnu.org/copyleft/gpl.html
*/

public class Main {
    static final float _log_e_10 = (float) Math.log(10.0);

    public static final float chopToNSignificantDigits(final float original, int no_of_sig_digits) {
        if (original == 0f)
            return 0f;

        /* a plain float->int conversion (which is a 'trunc' in java)
            instead of the 'floor' won't be correct if the argument is
            negative (eg original = 1.23e-7) */
        final int exp = (int) Math.floor((float) Math.log(Math.abs(original)) / _log_e_10 - no_of_sig_digits + 1f);

        /* it's important to use double here! else, '1e{exp}' may be
            <Float.MIN_VALUE for a very small 'original' */
        final double mult = Math.pow(10.0, exp);

        return (float) (Math.round(original / mult) * mult);
    }
}

Related

  1. chopScheme(String path)
  2. chopScheme(String path)
  3. chopString(String argString, int argLength)
  4. chopString(String str, int len)
  5. chopString(String title, int maxLen)
  6. chopTrailingChars(String source, char[] chars)