Here you can find the source of toScientificNotation(BigDecimal bd)
1.234E-5
1.00E5
1E2
bd
has a precision higher than 20, this method will truncate the output string to have a precision of 20 (no rounding will be done, just a truncate).
public static String toScientificNotation(BigDecimal bd)
//package com.java2s; /*/*from w ww .j a v a2s . c om*/ // Licensed to DynamoBI Corporation (DynamoBI) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. DynamoBI licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. */ import java.math.*; public class Main { /** * Formats a {@link BigDecimal} value to a string in scientific notation For * example<br> * * <ul> * <li>A value of 0.00001234 would be formated as <code>1.234E-5</code></li> * <li>A value of 100000.00 would be formated as <code>1.00E5</code></li> * <li>A value of 100 (scale zero) would be formated as <code> * 1E2</code></li><br> * If <code>bd</code> has a precision higher than 20, this method will * truncate the output string to have a precision of 20 (no rounding will be * done, just a truncate). */ public static String toScientificNotation(BigDecimal bd) { final int truncateAt = 20; String unscaled = bd.unscaledValue().toString(); if (bd.signum() < 0) { unscaled = unscaled.substring(1); } int len = unscaled.length(); int scale = bd.scale(); int e = len - scale - 1; StringBuilder ret = new StringBuilder(); if (bd.signum() < 0) { ret.append('-'); } //do truncation unscaled = unscaled.substring(0, Math.min(truncateAt, len)); ret.append(unscaled.charAt(0)); if (scale == 0) { // trim trailing zeroes since they aren't significant int i = unscaled.length(); while (i > 1) { if (unscaled.charAt(i - 1) != '0') { break; } --i; } unscaled = unscaled.substring(0, i); } if (unscaled.length() > 1) { ret.append("."); ret.append(unscaled.substring(1)); } ret.append("E"); ret.append(e); return ret.toString(); } }