Javascript split integer and add decimal point - javascript

My integer value is 1210 and i want split this integer like 1 | 210 .Have to add decimal point on middle.
Eg:
var integer=1210;
Split this integer and add decimal value like this 1.210

Why don't you just divide the number by 1000
var x = 1210;
var y = 1210/1000; //1.210 number
var z = y+""; // 1.120 will be string here
console.log(y); // Will output 1.210

If you're always dealing with 4 digit numbers, dividing by 1000 will work (as mentioned in another answer) but you'll need to use toFixed to make sure javascript doesn't remove trailing zeros:
var x = 1210;
(x / 1000).toFixed(3) // => "1.210"
(x / 1000) + "" // => "1.21"

More generically you could use:
x=prompt('enter an integer');
xl=x.toString().length-1
alert((x/Math.pow(10,xl)).toFixed(xl));
(just make sure you enter an integer, preferably +ve, at the prompt)

Related

javascript random 8digits in specific number

I'm trying to random 8 digits number 0-7 , but without the 8 and 9
this is what I've done, but I can't exclude the 8 and 9
var b = Math.floor(Math.random()*90000000) + 10000000;
console.log(b)
is there any quick for random the exact 8 digits exclude number? or do I really have to random one by one and += until 8 digits ?
Convert to octal (which contains only the digits 0-7) and trim to the desired length:
b.toString(8).substr(0, 8)
You could get first the max number of the octal system with 8 places and use the decimal system for generating the random value and convert it back to the wanted system.
var max = parseInt(100000000, 8);
console.log(('0000000' + Math.floor(Math.random() * max).toString(8)).slice(-8));
You need a number of 8 digits in base 8.
This means you're looking for a (decimal) number between 8^7 and 8^8-1, converted to base 8.
This should do the trick :
// initialize min and max values
var vmin = Math.pow(8,7);
var vmax = Math.pow(8,8)-1;
// compute random number within range
var dec = Math.floor(Math.random()*(vmax-vmin))+vmin;
// convert to base 8
console.log(dec.toString(8));
Perhaps you would want something more like this:
var b = Math.floor(Math.random()*8);
console.log(b);

parseInt() doesn't regard leading zeros, even with radix

When I want to convert a binary string to a base 10 decimal (Like this: parseInt('0001010', 2)), Javascript returns a decimal number, but a version in which the leading zeros mentioned in the example above have been disregarded. Is there any way to fix this?
So supposing you have the number '00000101101101':
var number = '00000101101101';
var length = number.length;
var decimal_number = parseInt(number, 2);
// going back
var new_number = decimal_number.toString(2);
var new_length = new_number.length;
var n_zeros = length - new_length;
var zeros = (n_zeros >= 2 ? Array(n_zeros+1).join("0") : "0");
new_number = zeros + new_number;
The decimal representation has no way to keep track of leading zeros. If you wish to keep the leading zeros in the result, you need a fundamentally different approach (e.g. keeping the output as a string).
Alternatively, if you know the width of the result a priori, you could just pad it with leading zeros on output.

Javascript: Convert a string representation of money to Number

Lets say I have an amount in string format like this:
amount = '12,000.00'
I want to convert it into a Number (Javascript) or a float.
parseFloat(amount) // this gives me 12 as a result
Number(amount) // this gives me NaN as a result
Other solution I thought was this:
parseFloat(amount.replace(/[,]/g, ''))
This works fine. But the problem here is the Locale.
This would fail when the amount is € 12000,00.
Here ',' has altogether a different meaning.
I looked around for a good solution but couldn't. I am looking for a generalized solution.
This is not that easy, as you can't exactly know what's the delimiter for thousands and what for the decimal part
Consider "12.000.000" is it 12000.000 === 12000 or 12000000?
But if you would set the requirement that the last delimiter is always the decimal delimiter -
meaning if at least one delimiter is given, the last one has to be the decimal delimiter, *if the digits following, don't exceed a defined length.
Then you could try the following
Edit
(see the revs if you're interested in the old function)
I put in the ability to define the max length of digits after the last delimiter "," or "." up until it is treated as float, after that its returned as integer
var amounts = ["12000","12.000,00", "12,000.00", "12,000,01", "12.000.02", "12,000,001"];
formatMoney.maxDecLength = 3; //Set to Infinity o.s. to disable it
function formatMoney(a) {
var nums = a.split(/[,\.]/);
var ret = [nums.slice(0, nums.length - 1).join("")];
if (nums.length < 2) return +nums[0];
ret.push(nums[nums.length - 1]);
return +(ret.join(nums[nums.length - 1].length < formatMoney.maxDecLength ? "." : ""));
}
for ( var i=0,j;j=amounts[i];i++)
console.log (j + " -> " +formatMoney(j));
Gives the output:
"12000 -> 12000"
"12.000,00 -> 12000"
"12,000.00 -> 12000"
"12,000,01 -> 12000.01"
"12.000.02 -> 12000.02"
"12,000,001 -> 12000001" //as you can see after the last "," there are 3 digits and its treated as integer
Another JSBin
You can get the local decimal delimiter in this manner:
1.1.toLocaleString().substr(1,1)
Before parse float, you could make sure the string contains nothing but numbers, possibly a minus sign, and the local decimal delimiter.
The truth is, you'll never know the format. 12,345. Is that 12345, or another locale version if 12.345?
However, if you have consistent decimals, then you'd be able to use the lastIndexOf function on a comma and a period will reveal the decimal position and character.
var price = '12,345.67';
var lastPeriod = price.lastIndexOf('.');
var lastComma = price.lastIndexOf(',');
if (lastComma != -1 && lastComma > lastPeriod) {
decimalCharacter = ',';
} else {
decimalCharacter = '.';
}
console.log(decimalCharacter); //. or , based on how the price string looks - see below
If price is 12,345.67, decimalCharacter will be .. If it's 12.345,67, it'll be returned as ,.

Truncate decimal number (as strings) to a fixed number of places

I want to truncate numbers (given as strings) to a fixed number of decimal places. The numbers can be negative (with a minus sign), positive (no sign). I'd prefer to round the numbers properly and keep trailing zeroes. I want the same number of decimal places, no matter how long the whole number is. The numbers will be stored back as strings.
For example:
140.234234234 -> 140.234
1.123123 -> 1.123
-12.789789 -> -12.790
First parse them as floats, then format with toFixed:
var nums = [
"140.234234234", // -> 140.234
"1.123123", // -> 1.123
"-12.789789" // -> -12.790
];
nums.forEach(function(n) {
console.log(parseFloat(n).toFixed(3));
});
http://codepen.io/anon/pen/IvxmA
Any number can be displayed as a fixed decimal place string by using .toFixed:
var num = 140.234234234;
var fixedDecimalPlace = num.toFixed(3); // is "140.234"
function truncate( numberString, trunk ) {
var onpoint = numberString.split('.',2);
var numberStringTruncated = numberString;
if (onpoint.length > 1) {
numberStringTruncated = onpoint[0] + '.' + onpoint[1].substring(0,trunk);
}
return numberStringTruncated;
}
This does not consider rounding or padding. As the other answer suggested, you should use parseFloat followed by toFixed

JavaScript displaying a float to 2 decimal places

I wanted to display a number to 2 decimal places.
I thought I could use toPrecision(2) in JavaScript .
However, if the number is 0.05, I get 0.0500. I'd rather it stay the same.
See it on JSbin.
What is the best way to do this?
I can think of coding a few solutions, but I'd imagine (I hope) something like this is built in?
float_num.toFixed(2);
Note:toFixed() will round or pad with zeros if necessary to meet the specified length.
You could do it with the toFixed function, but it's buggy in IE. If you want a reliable solution, look at my answer here.
number.parseFloat(2) works but it returns a string.
If you'd like to preserve it as a number type you can use:
Math.round(number * 100) / 100
Don't know how I got to this question, but even if it's many years since this has been asked, I would like to add a quick and simple method I follow and it has never let me down:
var num = response_from_a_function_or_something();
var fixedNum = parseFloat(num).toFixed( 2 );
with toFixed you can set length of decimal points like this:
let number = 6.1234
number.toFixed(2) // '6.12'
but toFixed returns a string and also if number doesn't have decimal point at all it will add redundant zeros.
let number = 6
number.toFixed(2) // '6.00'
to avoid this you have to convert the result to a number. you can do this with these two methods:
let number1 = 6
let number2 = 6.1234
// method 1
parseFloat(number1.toFixed(2)) // 6
parseFloat(number2.toFixed(2)) // 6.12
// method 2
+number1.toFixed(2) // 6
+number2.toFixed(2) // 6.12
Try toFixed instead of toPrecision.
function round(value, decimals) {
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
round(1.005, 2); // return 1.01
round(1.004, 2); // return 1 instead of 1.00
The answer is following this link: http://www.jacklmoore.com/notes/rounding-in-javascript/
I used this way if you need 2 digits and not string type.
const exFloat = 3.14159265359;
console.log(parseFloat(exFloat.toFixed(2)));
You could try mixing Number() and toFixed().
Have your target number converted to a nice string with X digits then convert the formated string to a number.
Number( (myVar).toFixed(2) )
See example below:
var myNumber = 5.01;
var multiplier = 5;
$('#actionButton').on('click', function() {
$('#message').text( myNumber * multiplier );
});
$('#actionButton2').on('click', function() {
$('#message').text( Number( (myNumber * multiplier).toFixed(2) ) );
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<button id="actionButton">Weird numbers</button>
<button id="actionButton2">Nice numbers</button>
<div id="message"></div>
The toFixed() method formats a number using fixed-point notation.
and here is the syntax
numObj.toFixed([digits])
digits argument is optional and by default is 0. And the return type is string not number. But you can convert it to number using
numObj.toFixed([digits]) * 1
It also can throws exceptions like TypeError, RangeError
Here is the full detail and compatibility in the browser.
let a = 0.0500
a.toFixed(2);
//output
0.05
There's also the Intl API to format decimals according to your locale value. This is important specially if the decimal separator isn't a dot "." but a comma "," instead, like it is the case in Germany.
Intl.NumberFormat('de-DE').formatToParts(0.05).reduce((acc, {value}) => acc += value, '');
Note that this will round to a maximum of 3 decimal places, just like the round() function suggested above in the default case. If you want to customize that behavior to specify the number of decimal places, there're options for minimum and maximum fraction digits:
Intl.NumberFormat('de-DE', {minimumFractionDigits: 3}).formatToParts(0.05)
float_num = parseFloat(float_num.toFixed(2))
I have made this function. It works fine but returns string.
function show_float_val(val,upto = 2){
var val = parseFloat(val);
return val.toFixed(upto);
}

Categories

Resources