如何移动小数? [英] How to move decimal?

查看:83
本文介绍了如何移动小数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,我想定义小数点后的位置.我只能在示例中真正地展示它.

In JavaScript, I want to define where the decimal place goes. I can only really show it in example.

让我们说输入值为1234.
我希望输出为123.4.

Lets say the input value is 1234.
I want the output to be 123.4.

或者,如果输入为12345,我希望输出为123.45.

Or, if the input is 12345, I want the output to be 123.45.

或者,如果输入为123456,我希望输出为123.456.你得到图片了.

Or, if the input is 123456, I want the output to be 123.456. You get the picture.

为澄清起见,我只想在小数点左边加上三位数.总位数未知.

To clarify, I just want three digits on the left side of the decimal. The total number of digits is unknown.

那么,怎么办呢?

推荐答案

var n = 1234;
var l = n.toString().length-3;
var v = n/Math.pow(10, l); // new value

3是因为您希望将前3个数字作为一个整体,所以基数会根据n的大小而变化.

The 3 is because you want the first 3 digits as wholes, so the base changes depending on the size of n.

function moveDecimal(n) {
  var l = n.toString().length-3;
  var v = n/Math.pow(10, l);
  return v;
}

尝试使用1234、12345和123456.

Try it for 1234, 12345 and 123456.

这篇关于如何移动小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆