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

问题描述 投票:0回答:3

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

假设原始变量值为100,

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

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

<div class="original"></div>

var original = data['result'];
$(".original").html(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

我怎样才能做到这一点?

javascript jquery arrays decimal-point
3个回答
2
投票

编辑

原来这个数字应该被认为是一个字符串...... 因为整个AND小数(总是18)是“合并”(点被删除)。

另外......对于简单的JS,我们正在处理一个“太大”的整数。 所以这里有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>

1
投票

如果您的号码表示为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

0
投票

你应该使用Number.toFixed(len)

let a = (100).toFixed(18).toString().split('.');
document.body.innerHTML = a[0]+' | ' + a[1];
© www.soinside.com 2019 - 2024. All rights reserved.