最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Scale and Precision from Number - Stack Overflow

programmeradmin2浏览0评论

I'm looking to get the scale and precision from a number in the following example.

var x = 1234.567;

I'm not seeing any .scale or .precision functions built in and I'm not sure what the best way to right one is.

I'm looking to get the scale and precision from a number in the following example.

var x = 1234.567;

I'm not seeing any .scale or .precision functions built in and I'm not sure what the best way to right one is.

Share Improve this question edited Jun 8, 2012 at 17:07 thecodeparadox 87.1k22 gold badges141 silver badges164 bronze badges asked Jun 8, 2012 at 16:42 Code JunkieCode Junkie 7,78827 gold badges86 silver badges146 bronze badges 5
  • What are those scale and precision ? Do you mean the numbers of digits on each side of the point ? – Denys Séguret Commented Jun 8, 2012 at 16:45
  • convert to a string and then do split and see the string length. – Chetter Hummin Commented Jun 8, 2012 at 16:46
  • Does that make any sense with floating point? Consider 0.1 + 0.1 + 0.1. You'd expect that to be 0.3. Well it's not. It's 0.30000000000000004. Suddenly, your precision has shot up. – Eric Commented Jun 8, 2012 at 17:36
  • @Eric He doesn't use the numbers for calculation. – VisioN Commented Jun 8, 2012 at 17:39
  • @VisioN: Even so, there are floating point problems here. If you're not going to use numbers to calculate, store them as a string! – Eric Commented Jun 8, 2012 at 17:57
Add a comment  | 

3 Answers 3

Reset to default 7

You can use Number.prototype.toFixed()

var x = 1234.56780123;
    
x.toFixed(2); // output: 1234.57
x.toFixed(3); // output: 1234.568
x.toFixed(4); // output: 1234.5680
var x = 1234.567;

var parts = x.toString().split('.');

parts[0].length; // output: 4 for 1234

parts[1].length; // output: 3 for 567

NOTE

Javascript has toPrecision() method that gives to a number with specified length.

For example:

var x = 1234.567;

x.toPrecision(4); // output: 1234

x.toPrecision(5); // output: 1234.5

x.toPrecision(7); // output: 1234.56

But

x.toPrecision(5); // output: 1235

x.toPrecision(3); // output: 1.23e+3 

and so on.

According to comment

Is there a way to check that the string contain .?

var x = 1234.567

x.toString().indexOf('.'); // output: 4

Note

.indexof() return first index of target else -1.

Another advanced solution (if I correctly understand what you mean by scale and precision):

function getScaleAndPrecision(x) {
    x = parseFloat(x) + "";
    var scale = x.indexOf(".");
    if (scale == -1) return null;
    return {
        scale : scale,
        precision : x.length - scale - 1
    };
}

var res = getScaleAndPrecision(1234.567);

res.scale;       // for scale
res.precision;   // for precision

If number is not float function returns null.

发布评论

评论列表(0)

  1. 暂无评论