Если у вас все в порядке с анализом ввода n
в строку и выводом его в виде строки out
, он становится обработкой строки:
function toSpecialExponential(n){
if(isNaN(n)) return NaN;
//E.G. n = 1.3844e43;
var splitN = parseFloat(n).toExponential().split("e"); //["1.3844","+43"]
var frontN = parseFloat(splitN[0]); //1.3884
var expo = parseInt(splitN[1]); //43
//Get modu = expo (mod 3)
//Note that you cannot properly get the modulus of a negative number in JS, so we have to turn negative numbers positive as well...
//Also indicator of how much to shift the decimal point by
var modu = Math.abs(expo)%3;
//Special Case: expo is divisible by 3
if(modu == 0) return parseFloat(n).toExponential().replace("+",""); //return n as is, parsed as an exponential but with the + signs removed. (1 => "1e+0")
//Actual Parsing
//Now with support for negative numbers
var newExpo = (expo<0)?-((3-expo)-modu):expo-modu;
var newFront = (expo<0)?frontN*Math.pow(10,3-modu):frontN*Math.pow(10,modu);
//Hack to avoid floating point errors
var _len = frontN.toString().replace(/([^0-9]+)/gi,"").length-Math.abs(expo-newExpo)-1;
newFront = parseFloat(newFront).toFixed(_len);
return newFront+"e"+newExpo;
}
РЕДАКТИРОВАТЬ:
- JS Snippet
- Небольшой хак для избавления от ошибок с плавающей запятой.
- Поддержка отрицательных чисел и показателей
function toSpecialExponential(n){
if(isNaN(n)) return NaN;
//E.G. n = 1.3844e43;
var splitN = parseFloat(n).toExponential().split("e"); //["1.3844","+43"]
var frontN = parseFloat(splitN[0]); //1.3884
var expo = parseInt(splitN[1]); //43
//Get modu = expo (mod 3)
//Note that you cannot properly get the modulus of a negative number in JS, so we have to turn negative numbers positive as well...
//Also indicator of how much to shift the decimal point by
var modu = Math.abs(expo)%3;
//Special Case: expo is divisible by 3
if(modu == 0) return parseFloat(n).toExponential().replace("+",""); //return n as is, parsed as an exponential but with the + signs removed. (1 => "1e+0")
//Actual Parsing
//Now with support for negative numbers
var newExpo = (expo<0)?-((3-expo)-modu):expo-modu;
var newFront = (expo<0)?frontN*Math.pow(10,3-modu):frontN*Math.pow(10,modu);
//Hack to avoid floating point errors
var _len = frontN.toString().replace(/([^0-9]+)/gi,"").length-Math.abs(expo-newExpo)-1;
newFront = parseFloat(newFront).toFixed(_len);
return newFront+"e"+newExpo;
}
<input type="text" id="input" value="1.3844e43" /> <input type="button" onclick="javascript:document.getElementById('out').innerHTML = toSpecialExponential(document.getElementById('input').value)" value="Get Special Exponential!">
<h3>Output</h3>
<div id="out"></div>