Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Leading and trailing zeros in numbers

I am working on a project where I require to format incoming numbers in the following way:

###.###

However I noticed some results I didn't expect. The following works in the sense that I don't get an error:

console.log(07);

// or in my case:
console.log(007);

Of course, it will not retain the '00' in the value itself, since that value is effectively 7.

The same goes for the following:

console.log(7.0);

// or in my case:
console.log(7.000);

JavaScript understands what I am doing, but in the end the actual value will be 7, which can be proven with the following:

    const leadingValue = 007;
    const trailingValue = 7.00;

    console.log(leadingValue, trailingValue); // both are exactly 7

But what I find curious is the following: the moment I combine these two I get a syntax error:

// but not this:
console.log(007.000);

1) Can someone explain why this isn't working?

I'm trying to find a solution to store numbers/floats with the exact precision without using string.

2) Is there any way in JS/NodeJS or even TypeScript to do this without using strings?

What I currently want to do is to receive the input, scan for the format and store that as a separate property and then parse the incoming value since parseInt('007.000') does work. And when the user wants to get this value return it back to the user... in a string.. unfortunately.

like image 526
Kai Avatar asked Mar 04 '23 23:03

Kai


1 Answers

1) 007.000 is a syntax error because 007 is an octal integer literal, to which you're then appending a floating point part. (Try console.log(010). This prints 8.)

2) Here's how you can achieve your formatting using Intl.NumberFormat...

var myformat = new Intl.NumberFormat('en-US', { 
    minimumIntegerDigits: 3, 
    minimumFractionDigits: 3 
});
console.log(myformat.format(7)); // prints 007.000
like image 122
Martin Stone Avatar answered Mar 13 '23 05:03

Martin Stone