如何在 jQuery 的两个不同变量中获取一些第一个字符和其余字符?

How to get some first characters and the rest of the characters in two different variables in jQuery?

我有一个有 18 个小数点的数字。 我想获取一个变量中小数点前的数字和另一个变量中小数点后的数字。

假设原来的变量值为100,

我想像这样显示 100.000000000000000000 但现在我得到 100000000000000000000(没有小数点)

我试图在 HTML 元素中打印小数点前的数字,在另一个 HTML

中打印其余数字
<div class="original"></div>

var original = data['result'];
$(".original").html(original]);

这会在元素 original 中打印 100000000000000000000,没问题。

现在我想打印 HTML 元素 'beforeDecimal' 中小数点前的数字,然后指向其余部分

所以我的加分是:

<div class="beforeDecimal"></div> . <div class="afterDecimal"></div>

var beforeDecimal = data['result']; // how do I have to change this ?
$(".beforeDecimal").html(beforeDecimal]);

var afterDecimal = data['result']; // how do I have to change this ?
$(".afterDecimal").html(afterDecimal]);

如果我使用 var beforeDecimal = parseFloat(data['result']).toFixed(4); 显示 100.00000000000e+21 但我想要 100 . 000000000000000000

我该怎么做?

你应该使用Number.toFixed(len)

let a = (100).toFixed(18).toString().split('.');
document.body.innerHTML = a[0]+' | ' + a[1];

编辑

原来数字应该被认为是一个字符串...
因为整个 AND 小数点(总是 18)是 "merged"(点被删除)。

此外...我们正在为简单的 JS 使用 "too big" 整数。
所以 BigInteger.js 来了,它使我们能够将这个大数字无误地转换为字符串。

那么,那就是子串管理!

这个不错!
;)

$(document).ready(function(){

  // Our start point...
  var data = [];
  data['result'] = 2287852333330000000000;

  // To see why use "bigInt" library !!!
  var numberWRONG = data['result'].toString();
  console.log("numberWRONG: "+numberWRONG);


  var number = bigInt(data['result']);
  console.log(number);
  
  numberString = number.toString();
  console.log(numberString);

  // Now were ok to just string manipulate... Knowing we always have 18 decimals.
  
  // Get the lenghts.
  var numberLength = numberString.length;
  var entireLength = numberLength - 18;
  var decimalLength = numberLength - entireLength;
  
  // cut the sub-strings.
  var entire = numberString.substr(0,entireLength);
  var decimals = numberString.substr(entireLength,numberLength);
  
  // Append the parts in the right divs.
  $(".beforeDecimal").html(entire);
  $(".afterDecimal").html(decimals);
});
div{
  display:inline-block;
}
.beforeDecimal{
  color:blue;
}
.afterDecimal{
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.26/BigInteger.min.js"></script>

<div class="beforeDecimal"></div> . <div class="afterDecimal"></div>

如果您的号码表示为 javascript 字符串,您可以

const [before, after] = floatAsString.split('.');

如果是数字,你使用

const [before, after] = float.toFixed(18).split('.');

我建议不要使用涉及减法的浮点计算,因为它们会在输出中产生小错误。考虑以下示例:

const float = 1.4543;
const integerPart = float | 0; // this removes the fractional part
const fraction = float - integerPart;
console.log(fraction); // logs 0.4542999999999999, which is not the actual fraction, but is very close to it