How to Get number with 2 decimal and not rounding using javascript? - javascript

How to Get number with 2 decimal and not rounding using javascript ?
i try
http://jsfiddle.net/3AaAx/31/
var i = "1234.666";
var xxx = Math.floor(i * 100) / 100
alert(xxx);
AND
http://jsfiddle.net/3AaAx/29/
var i = "1234.666";
function myToFixed(i, digits) {
var pow = Math.pow(10, digits);
return Math.floor(i * pow) / pow;
}
var xxx = myToFixed(i, 2)
alert(xxx);
it's work.
But when i declare var i = "1234"; i want to get "1234.00"
http://jsfiddle.net/3AaAx/30/
http://jsfiddle.net/3AaAx/32/
How to do that ?

Not rounding is an unusual requirement, and it's too bad because if you were okay with rounding, you could just use toFixed:
var num = 1234.5678;
snippet.log(num.toFixed(2)); // "1234.57" -- note the rounding!
var num = 1234.5678;
snippet.log(num.toFixed(2)); // "1234.57" -- note the rounding!
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
(And no, you can't just do .toFixed(3) and then chop off the last digit; rounding doesn't necessarily only change the last digit, consider using toFixed(3) on 1111.9999, which gives you 1112.000. Just chopping off the last digit of that still gives you a rounded result.)
To do it without rounding, I don't think there's much available but brute force:
// Assumes `digits` is never more than 20
function toFixedNoRounding(num, digits) {
var parts = String(num).split('.');
if (digits <= 0) {
return parts[0];
}
var fractional = (parts[1] || "0") + "000000000000000000000";
return parts[0] + "." + fractional.substring(0, digits);
}
// Assumes `digits` is never more than 20
function toFixedNoRounding(num, digits) {
var parts = String(num).split('.');
if (digits <= 0) {
return parts[0];
}
var fractional = (parts[1] || "0") + "000000000000000000000";
return parts[0] + "." + fractional.substring(0, digits);
}
var num, notRounded;
num = 1234;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
num = 1234.5678;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
num = 1234.1;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
num = 1234.999999;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Or you can use indexOf, but it seems a lot clunkier:
// Assumes `digits` is never more than 20
function toFixedNoRounding(num, digits) {
var str = String(num);
var n = str.indexOf(".") + 1;
if (n === 0) {
str += ".";
n = str.length;
}
n = digits <= 0 ? n - 1 : n + digits;
if (str.length !== n) {
str = (str + "00000000000000000000").substring(0, n);
}
return str;
}
// Assumes `digits` is never more than 20
function toFixedNoRounding(num, digits) {
var str = String(num);
var n = str.indexOf(".") + 1;
if (n === 0) {
str += ".";
n = str.length;
}
n = digits <= 0 ? n - 1 : n + digits;
if (str.length !== n) {
str = (str + "00000000000000000000").substring(0, n);
}
return str;
}
var num, notRounded;
num = 1234;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
num = 1234.5678;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
num = 1234.1;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
num = 1234.999999;
notRounded = toFixedNoRounding(num, 2);
snippet.log(num + " => " + notRounded);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

var y = "1234.045";
var s = number_with_2_decimal(y);
alert(s);
function number_with_2_decimal(a) {
var x = Math.floor(a * 100) * 0.01;
var str = String(x);
var n = str.indexOf('.');
if (n === -1) {
str += '.00';
};
return str;
}

Related

Sorting an integer without using string methods and without using arrays

can anyone come with an idea of how to sort an integer without using an array, and without using string methods as well as sort() method?
for example
input: 642531
output: 123456
I started by writing 2 simple functions - one which checks the length of the number, the other one splits the integer at some point and switches between 2 desired numbers. Below are the 2 functions.
I got stuck with the rest of the solution...
function switchDigits(num, i) { // for input: num=642531, i = 4 returns 624135
let temp = num;
let rest = 0;
for (let j = 0; j < i - 1; j++) {
rest = rest * 10;
rest = rest + temp % 10;
temp = (temp - temp % 10) / 10;
}
let a = temp % 10;
temp = (temp - a) / 10;
let b = temp % 10;
temp = (temp - b) / 10;
temp = Math.pow(10, i - 2) * temp;
temp = temp + 10 * a + b;
temp = Math.pow(10, i - 1) * temp;
temp = temp + rest;
return temp;
}
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
let num = 642534;
let i = checkHowManyDigits(num);
console.log(switchDigits(num));
It actually complicated requirement and so does this answer. It's pure logic and as it is it's a question from a test you should try understanding the logic on your own as a homework.
function checkHowManyDigits(num) { //input: 642534, output: 6 (length of the integer)
let count = 0;
while (num > 0) {
let a = num % 10;
num = (num - a) / 10;
count++;
}
return count;
}
function sortDigit(numOriginal) {
let i = checkHowManyDigits(numOriginal);
let minCount = 0;
let min = 10;
let num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d < min) {
min = d;
minCount = 0;
} else if (d === min) {
minCount++;
}
}
let result = 0;
while (minCount >= 0) {
result += min * Math.pow(10, i - minCount - 1);
minCount--;
}
let newNum = 0;
num = numOriginal;
while (num > 0) {
let d = num % 10;
num = (num - d) / 10;
if (d !== min) {
newNum = newNum * 10 + d;
}
}
if (newNum == 0) return result;
else return result += sortDigit(newNum);
}
console.log(sortDigit(642531));
You could have a look to greater and smaller pairs, like
64
46
The delta is 18, which gets an idea if you compare other pairs, like
71
17
where the delta is 54. Basically any difference of two digits is a multiple of 9.
This in mind, you get a function for taking a single digit out of a number and a single loop who is sorting the digits by using the calculated delta and subtract the value, adjusted by the place.
function sort(number) {
const
getDigit = e => Math.floor(number / 10 ** e) % 10,
l = Math.ceil(Math.log10(number)) - 1;
let e = l;
while (e--) {
const
left = getDigit(e + 1),
right = getDigit(e);
if (left <= right) continue;
number += (right - left) * 9 * 10 ** e;
e = l;
}
return number;
}
console.log(sort(17)); // 17
console.log(sort(71)); // 17
console.log(sort(642531)); // 123456
console.log(sort(987123654)); // 123456789
So eventually I found the best solution.
*This solution is based on a Java solution I found in StackOverFlow forums.
let store = 0;
function getReducedNumbr(number, digit) {
console.log("Remove " + digit + " from " + number);
let newNumber = 0;
let repeateFlag = false;
while (number>0) {
let t = number % 10;
if (t !== digit) {
newNumber = (newNumber * 10) + t;
} else if (t == digit) {
if (repeateFlag) {
console.log(("Repeated min digit " + t + " found. Store is : " + store));
store = (store * 10) + t;
console.log("Repeated min digit " + t + " added to store. Updated store is : " + store);
} else {
repeateFlag = true;
}
}
number = Math.floor(number / 10);
}
console.log("Reduced number is : " + newNumber);
return newNumber;}
function sortNum(num) {
let number = num;
let original = number;
let digit;
while (number > 0) {
digit = number % 10;
console.log("Last digit is : " + digit + " of number : " + number);
temp = Math.floor(number/10);
while (temp > 0) {
console.log("subchunk is " + temp);
t = temp % 10;
if (t < digit) {
digit = t;
}
temp = Math.floor(temp/10);
}
console.log("Smallest digit in " + number + " is " + digit);
store = (store * 10) + digit;
console.log("store is : " + store);
number = getReducedNumbr(number, digit);
}
console.log(("Ascending order of " + original + " is " + store));
return store;
}
console.log(sortNum(4214173));
you can see how it works here https://jsfiddle.net/9dpm14fL/1/

24-hours time automatic regex

This is my code:
let input = document.getElementById('f2f11c3');
input.addEventListener('input', addcommas, false);
function addcommas() {
var v = document.getElementById('f2f11c3');
var t = v.value.replace(/\D/g, '');
var i, temp = '';
for (i = t.length; i >= 0; i -= 2) {
if (i == t.length) {
temp = t.substring(i - 2, i);
} else {
if (t.substring(i - 2, i) != "")
temp = t.substring(i - 2, i) + ':' + temp;
}
if (i < 0) {
temp = t.substring(0, i + 2) + ':' + temp;
break;
}
}
v.value = temp;
}
<input type="text" value="" maxlength="8" id="f2f11c3" />
But entered numbers can be greater than 24. Can you fully adapt to the time format?
Example: 23:59:59 and one more 00:00:00
Short answer
Take the string
Split that
Use modulo operator to get the result
Example
var time="24:70:65"; // Suppose we have this time
var parts=time.split(":");// Split the time with :
var part1=(+parts[0] % 24)
var part2=(+parts[1] % 60)
var part3=(+parts[2] % 60)
// Now to get answer in two digits you can
part1 = ("0" + part1).slice(-2);
part2 = ("0" + part2).slice(-2);
part3 = ("0" + part3).slice(-2);
console.log(`${part1}:${part2}:${part3}`)
Hope this will work

How do I increment a string with numbers?

I need to increment a value similar to this:
A001 becomes A002
A999 becomes B001
B001 becomes B002
etc
Z999 becomes A001
I can increment an integer like this:
var x = 5;
x++;
Yields x = 6
I can increment an character like this:
var str = 'A';
str = ((parseInt(str, 36)+1).toString(36)).replace(/0/g,'A').toUpperCase();
if (str =='1A') {
str = 'A';
}
Yields the next character in the alphabet.
This code seems to work, but I'm not sure it's the best way?
var str = 'Z999';
if (str == 'Z999') {
results = 'A001';
}
else {
var alpha = str.substring(0,1);
num = str.substring(1,4);
if (alpha != 'Z' && num == '999') {
alpha= ((parseInt(alpha, 36)+1).toString(36)).replace(/0/g,'A').toUpperCase();
}
num++;
var numstr = num + "";
while (numstr .length < 3) numstr = "0" + numstr ;
if (numstr == 1000) {
numstr = '001';
}
results = alpha + numstr;
}
results seems to give the correct answer. Yes?
You could use parseInt(input.match(/\d+$/), 10) to extract the number at the end of the string and input.match(/^[A-Za-z]/) to retreive the single character at the beginning.
Increment and pad the number accordingly, and increment the character if the number is over 999 by retrieving the character's character code and incrementing that.
String.fromCharCode(letter.charCodeAt(0) + 1);
Full code/example:
function incrementNumberInString(input) {
var number = parseInt(input.trim().match(/\d+$/), 10),
letter = input.trim().match(/^[A-Za-z]/)[0];
if (number >= 999) {
number = 1;
letter = String.fromCharCode(letter.charCodeAt(0) + 1);
letter = letter === '[' ? 'A': (letter === '{' ? 'a' : letter);
} else {
number++;
}
number = '000'.substring(0, '000'.length - number.toString().length) + number;
return letter + number.toString();
}
document.querySelector('pre').textContent =
'A001: ' + incrementNumberInString('A001')
+ '\nA999: ' + incrementNumberInString('A999')
+ '\nB001: ' + incrementNumberInString('B001')
+ '\nB044: ' + incrementNumberInString('B044')
+ '\nZ999: ' + incrementNumberInString('Z999');
<pre></pre>
Output:
A001: A002
A999: B001
B001: B002
B044: B045
D7777: E001
Try storing A-Z in an array , using String.prototype.replace() with RegExp /([A-Z])(\d+)/g to match uppercase characters , digit characters . Not certain what expected result is if "Z999" reached ?
var arr = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
var spans = document.querySelectorAll("span");
function count(el) {
var data = el.innerHTML.replace(/([A-Z])(\d+)/g, function(match, text, n) {
var _text, _n;
if (Number(n) === 999) {
_text = arr[ arr.indexOf(text) + 1 ];
} else {
_text = text
};
// `"Z999"` condition ?
if (_text === undefined) {
return "<mark>" + text + n + "</mark>"
}
_n = Number(n) + 1 < 1000 ? Number(n) + 1 : "001";
if (n < 10) {
return _text + n.slice(0, 2) + _n
};
if (n < 100) {
return _text + n.slice(0, 1) + _n
} else {
return _text + _n
}
});
el.innerHTML = data
}
for (var i = 0; i < spans.length; i++) {
count(spans[i])
}
<span>A001</span>
<span>A999</span>
<span>B001</span>
<span>C999</span>
<span>D123</span>
<span>Z999</span>

How to (always) add commas to decimal separator in JavaScript

I'm using the following script to use dots as the thousands separator and commas as decimals separator that I got from this question.
var numero = 1000.00;
function formatThousands(n, dp) {
var s = ''+(Math.floor(n)),
d = n % 1,
i = s.length,
r = '';
while ((i -= 3) > 0) {
r = '.' + s.substr(i, 3) + r;
}
return s.substr(0, i + 3) + r + (d ? ',' + Math.round(d * Math.pow(10,dp||2)) : '');
}
alert(formatThousands(numero,2));
/// http://jsperf.com/compare-two-format-thousands
See also jsfiddle
This is working OK, except for integers.
For example, the number 1000 will return 1.000 and I want it to return 1.000,00 since the numbers refer to Euro currency.
How can I add the 2 decimals (cents) in every number?
Thanks for helping!
Does this work?
function formatThousands(n, dp) {
var s = ''+(Math.floor(n)), d = n % 1, i = s.length, r = '';
while ( (i -= 3) > 0 ) { r = '.' + s.substr(i, 3) + r; }
s = s.substr(0, i + 3) + r + (d ? ',' + Math.round(d * Math.pow(10,dp||2)) : '');
return s.charAt(-1) != ',' ? s+',00' : s;
}
EDIT:
How about this?
function formatThousands(n, dp) {
n = (''+n).split('.');
i = n[0];
d = !(n[1]) ? '00' : n[1];
n = i.match(/.{4}/g).join('.');
return n + ',' + d;
}
http://jsfiddle.net/XC3sS/12/

javascript convert currency to thousands

I have a decimal number*(28045.124578)* and i want it to be converted so that it will show in thousand currency format($28.0K) using javascript.
I am using this script tp convert but this doesn't help
function kFormatter(num) {
num = num.toString().replace(/\$|\,/g, '');
if (isNaN(num))
{
num = "0";
}
num = Math.floor(num * 100 + 0.50000000001);
cents = num % 10;
num = Math.floor(num / 100000).toString();
//console.log('num=', num/1000);
if (cents < 10)
{
cents = "0" + cents;
}
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
{
num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
}
return num + '.' + cents;
}
but this doesn't help. Please suggest.
You can use round to get the nearest whole number.
function kformatter(num){
var newvalue = Math.round(num/100);
return newvalue?(newvalue/10)+"K":num;
}

Categories