Java Script toSci(BigDecimal bd, int sf)

Here you can find the source of toSci(BigDecimal bd, int sf)

Description

to Sci

License

Mozilla Public License

Declaration

public static String toSci(BigDecimal bd, int sf) 

Method Source Code

//package com.java2s;
/** This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 *//* ww w.j  av  a2 s  .c om*/

import java.text.*;
import java.math.*;
import javax.script.*;

public class Main {
    private static final ScriptEngine engine = (new ScriptEngineManager()).getEngineByName("javascript");

    public static String toSci(BigDecimal bd, int sf) {
        Double x = bd.doubleValue();
        if (x.equals(Double.POSITIVE_INFINITY) || x.equals(Double.NEGATIVE_INFINITY)) {
            return x.toString();
        } else {
            try {
                return toString(
                        Double.parseDouble(engine.eval("Number(" + x + ").toPrecision(" + sf + ")").toString()));
            } catch (Exception ex) {
                return toFix(bd, 15);
            }
        }
    }

    public static String toString(double x) {
        String str = x + "";
        if (str.matches(".*\\.0")) {
            str = str.substring(0, str.indexOf("."));
        }
        return str;
    }

    public static double toFix(double x, int dp) {
        String format = "";
        for (int i = 0; i < dp; i++) {
            format = format + "#";
        }
        return Double.parseDouble((new DecimalFormat("#0." + format)).format(x));
    }

    public static String toFix(BigDecimal x, int dp) {
        String format = "";
        for (int i = 0; i < dp; i++) {
            format = format + "#";
        }
        return (new DecimalFormat("#0." + format)).format(x);
    }
}

Related

  1. getScriptCompileMsg(ScriptException ex)
  2. getSpParamOfWeiboLogin(String pwd, String servicetime, String nonce)
  3. removeScript(String name)
  4. runScript(final String script)
  5. toMap(ScriptObjectMirror som, Class type)