Javascript Number to Roman Conversion [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I was looking to convert from Number to Roman (X, IV etc).
Someone proposed this solution, I'm going through the solution but I wasn't able to understand even though I debugged it.
Can someone explain what's going on? I'm just trying to learn some JS.
function convertToRoman(num) {
var roman = {"M" :1000, "CM":900, "D":500, "CD":400, "C":100, "XC":90, "L":50, "XL":40, "X":10, "IX":9, "V":5, "IV":4, "I":1};
str = "";
for (var i in roman ) {
var q = Math.floor(num / roman[i]); //Why?
num -= q * roman[i]; //Why?
str += i.repeat(q); //Why?
}
return str;
}

Description
Code described in comments below.
// this is a function declaration
// with a parameter called num
function convertToRoman(num) {
// this is an object, being used as a lookup
var roman = {"M" :1000, "CM":900, "D":500, "CD":400, "C":100, "XC":90, "L":50, "XL":40, "X":10, "IX":9, "V":5, "IV":4, "I":1};
console.log('num = ' + num);
// this is a variable of type string
str = "";
// for loop to go over each item in roman
for (var i in roman ) {
console.log('i = ' + i);
// calculates the Math Floor of the number passed in divided by the roman value
// this will do the number passed divided by 1000 first
// Example: convertToRoman(1201)
// Math.floor(1201 / 1000) = 1
var q = Math.floor(num / roman[i]); //Why?
console.log('q = ' + q);
// remove the value of q multiplied by roman[i]
// Example: convertToRoman(1201)
// q = 1
// num = num - 1 * 1000;
// this makes it so that num is less the roman symbol we just found
num -= q * roman[i]; //Why?
console.log('num = ' + num);
// this is to make the roman number string
// Example: num = 1201
// i = 1000
// q = 1
// str = str + "M";
// or
// num = 3102
// i = 1000
// q = 3
// str = str + "M" [repeated 3 times]
// str = 'MMM' at the end of this
str += i.repeat(q); //Why?
console.log('str = ' + str);
}
// return the string
return str;
}
console.log(convertToRoman(1201));

The var roman is an associative array with key being a string and value the decimal system value.
It's ordered descending in value.
The loop iterates the array calculating the max times each value at index is contained within the given number, and subtracting it from the number so that the new iteration can continue calculating the "rest"

Related

JavaScript increment of the the last decimal number

I'm trying to to increment the last decimal of a number from 1.234 to 1.235
var numb = 1.234;
numb.replace(/\d$/, numb + 1);
or let just say that the problem is like following
var oNumber = 1.34567
var oDecimalCount = 5
increaseNumber(oNumber, oDecimalCount){
oNumber += //increase the 5th(oDecimalCount) decimal place
}
You could do this :
count the numbers after the decimal point
use this number to remove the decimal point * 10^n
add 1
use the number to place the decimals back in place / 10^n
//I found this function here : https://www.tutorialspoint.com/decimal-count-of-a-number-in-javascript
const decimalCount = num => {
// Convert to String
const numStr = String(num);
// String Contains Decimal
if (numStr.includes('.')) {
return numStr.split('.')[1].length;
};
// String Does Not Contain Decimal
return 0;
}
let numb = 1.234;
let count = decimalCount(numb);
console.log(((numb * 10 ** count) + 1) / 10 ** count);
Im not sure I understand the question completely, but can't you just do it like this
let numb = 1.234;
numb += 0.001;

Spliting the binary string in half

I am trying to split binary number in half and then just add 4 zeroes.
For example for 10111101 I want to end up with only the first half of the number and make the rest of the number zeroes. What I want to end up would be 10110000.
Can you help me with this?
Use substring to split and then looping to pad
var str = '10111101';
var output = str.substring( 0, str.length/2 );
for ( var counter = 0; counter < str.length/2; counter++ )
{
output += "0";
}
alert(output)
try this (one-liner)
var binary_str = '10111101';
var padded_binary = binary_str.slice(0, binary_str.length/2) + new Array(binary_str.length/2+1).join('0');
console.log([binary_str,padded_binary]);
sample output
['10111101','10110000']
I guess you are using JavaScript...
"10111101".substr(0, 4) + "0000";
It's a bit unclear if you are trying to operate on numbers or strings. The answers already given do a good job of showing how to operate on a strings. If you want to operate with numbers only, you can do something like:
// count the number of leading 0s in a 32-bit word
function nlz32 (word) {
var count;
for (count = 0; count < 32; count ++) {
if (word & (1 << (31 - count))) {
break;
}
}
return count;
}
function zeroBottomHalf (num) {
var digits = 32 - nlz32(num); // count # of digits in num
var half = Math.floor(digits / 2);// how many to set to 0
var lowerMask = (1 << half) - 1; //mask for lower bits: 0b00001111
var upperMask = ~lowerMask //mask for upper bits: 0b11110000
return num & upperMask;
}
var before = 0b10111101;
var after = zeroBottomHalf(before);
console.log('before = ', before.toString(2)); // outputs: 10111101
console.log('after = ', after.toString(2)); // outputs: 10110000
In practice, it is probably simplest to covert your number to a string with num.toString(2), then operate on it like a string as in one of the other answers. At the end you can convert back to a number with parseInt(str, 2)
If you have a real number, not string, then just use binary arithmetic. Assuming your number is always 8 binary digits long - your question is kinda vague on that - it'd be simply:
console.log((0b10111101 & 0b11110000).toString(2))
// 10110000

How to split a number into its digits in Javascript?

I want to Split a number into its digit (for example 4563 to 4 , 5 , 6 , 3 ) then addiction this digits. (for example: 4+5+6+3=18)
I can write code for 3 digit or 2 digit and ... numbers seperately but I cant write a global code for each number.
so this is my code for 2 digit numbers:
var a = 23
var b = Math.floor(a/10); // 2
var c = a-b*10; // 3
var total = b+c; // 2+3
console.log(total); // 5
and this is my code for 3 digit numbers:
var a = 456
var b = Math.floor(a/100); // 4
var c = a-b*100; // 56
var d = Math.floor(c/10); // 5
var e = c-d*10; // 6
var total = b+d+e; // 4+5+6
console.log(total); // 15
but I cant write a code to work with each number.How can I write a global code for each number?
In modern browsers you can do an array operation like
var num = 4563;
var sum = ('' + num).split('').reduce(function (sum, val) {
return sum + +val
}, 0)
Demo: Fiddle
where you first create an array digits then use reduce to sum up the values in the array
var num = 4563;
var sum = 0;
while(num > 0) {
sum += num % 10;
num = Math.floor(num / 10);
}
console.log(sum);
Do number%10(modulus) and then number/10(divide) till the number is not 0
I hope the following example is useful to you:
var text="12345";
var total=0;
for (i=0;i<text.length;i++)
{
total+= parseInt(text[i]);
}
alert(total);
This solution converts the number to string, splits it into characters and process them in the callback function (prev is the result from the previous call, current is the current element):
var a = 456;
var sum = a.toString().split("").reduce(function(prev, current){
return parseInt(prev) + parseInt(current)
})
Here is how I would approach the problem. The trick I used was to split on the empty string to convert the string to an array and then use reduce on the array.
function digitSum(n) {
// changes the number to a string and splits it into an array
return n.toString().split('').reduce(function(result, b){
return result + parseInt(b);
}, 0);
}
As mentioned by several other posters (hat tip to my commenter), there are several other good answers to this question as well.
Here is my solution using ES6 arrow functions as call back.
- Convert the number into a string.
- Split the string into an array.
- Call the map method on that array.
- Callback function parse each digit to an array.
let number = 65535;
//USING MAP TO RETURN AN ARRAY TO DIGITS
let digits = number.toString()
.split("")
.map(num => parseInt(num));
//OUTPUT TO DOM
digits.forEach(
digit =>
document.querySelector("#out").innerHTML += digit + "<br>"
);
<p id="out"></p>
1) You can cast input number to string, using .toString() method and expand it into array with spread (...) operator
const splitNumber = n => [ ...n.toString() ]
2) Another short way - using recursion-based solution like:
const splitNumber = n => n ? [ ...splitNumber(n/10|0), n%10 ] : []

Wrong Convert amount

The following function works perfect, but when the amount over 1 million, the function don't work exactly.
Example:
AMOUNTPAID = 35555
The output is: 35.555,00 - work fine
But when the amount paid is for example: 1223578 (over 1 Million),
is the output the following output value: 1.223.235,00 (but it must be: 1.223.578,00) - there is a deviation of 343
Any ideas?
I call the function via HTML as follows:
<td class="tr1 td2"><p class="p2 ft4"><script type="text/javascript">document.write(ConvertBetrag('{{NETAMOUNT}}'))</script> €</P></TD>
#
Here ist the Javascript:
function Convertamount( amount ){
var number = amount;
number = Math.round(number * Math.pow(12, 2)) / Math.pow(12, 2);
number = number.toFixed(2);
number = number.toString();
var negative = false;
if (number.indexOf("-") == 0)
{
negative = true ;
number = number.replace("-","");
}
var str = number.toString();
str = str.replace(".", ",");
// number before decimal point
var intbeforedecimaln = str.length - (str.length - str.indexOf(","));
// number of delimiters
var intKTrenner = Math.floor((intbeforedecimaln - 1) / 3);
// Leading digits before the first dot
var intZiffern = (intbeforedecimaln % 3 == 0) ? 3 : (intbeforedecimaln % 3);
// Provided digits before the first thousand separator with point
strNew = str.substring(0, intZiffern);
// Auxiliary string without the previously treated digits
strHelp = str.substr(intZiffern, (str.length - intZiffern));
// Through thousands of remaining ...
for(var i=0; i<intKTrenner; i++)
{
// attach 3 digits of the nearest thousand group point to String
strNew += "." + strHelp.substring(0, 3);
// Post new auxiliary string without the 3 digits being treated
strHelp = strHelp.substr(intZiffern, (strHelp.length - intZiffern));
}
// attach a decimal
var szdecimal = str.substring(intbeforedecimaln, str.length);
if (szdecimal.length < 3 )
{
strNew += str.substring(intbeforedecimaln, str.length) + '0';
}
else
{
strNew += str.substring(intbeforedecimaln, str.length);
}
var number = strNew;
if (negative)
{
number = "- " + number ;
}
return number;
}
JavaScript's Math functions have a toLocaleString method. Why don't you just use this?
var n = (1223578.00).toLocaleString();
-> "1,223,578.00"
The locale you wish to use can be passed in as a parameter, for instance:
var n = (1223578.00).toLocaleString('de-DE');
-> "1.223.578,00"

Javascript adding zeros to the beginning of a string (max length 4 chars)

var number = 1310;
should be left alone.
var number = 120;
should be changed to "0120";
var number = 10;
should be changed to "0010";
var number = 7;
should be changed to "0007";
In all modern browsers you can use
numberStr.padStart(4, "0");
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
function zeroPad(num) {
return num.toString().padStart(4, "0");
}
var numbers = [1310, 120, 10, 7];
numbers.forEach(
function(num) {
var paddedNum = zeroPad(num);
console.log(paddedNum);
}
);
function pad_with_zeroes(number, length) {
var my_string = '' + number;
while (my_string.length < length) {
my_string = '0' + my_string;
}
return my_string;
}
try these:
('0000' + number).slice(-4);
or
(number+'').padStart(4,'0');
Here's another way. Comes from something I did that needs to be done thousands of times on a page load. It's pretty CPU efficient to hard code a string of zeroes one time, and chop as many as you need for the pad as many times as needed. I do really like the power of 10 method -- that's pretty flexible.
Anyway, this is as efficient as I could come up with:
For the original question, CHOOSE ONE of the cases...
var number = 1310;
var number = 120;
var number = 10;
var number = 7;
then
// only needs to happen once
var zeroString = "00000";
// one assignment gets the padded number
var paddedNum = zeroString.substring((number + "").length, 4) + bareNum;
//output
alert("The padded number string is: " + paddedNum);
Of course you still need to validate the input. Because this ONLY works reliably under the following conditions:
Number of zeroes in the zeroString is desired_length + 1
Number of digits in your starting number is less than or equal to your desired length
Backstory:
I have a case that needs a fixed length (14 digit) zero-padded number. I wanted to see how basic I could make this. It's run tens of thousands of times on a page load, so efficiency matters. It's not quite re-usable as-is, and it's a bit inelegant. Except that it is very very simple.
For desired n digits padded string, this method requires a string of (at least) n+1 zeroes. Index 0 is the first character in the string, which won't ever be used, so really, it could be anything.
Note also that string.substring() is different from string.substr()!
var bareNum = 42 + '';
var zeroString = "000000000000000";
var paddedNum = zeroString.substring(bareNumber.length, 14) + bareNum
This pulls zeroes from zeroString starting at the position matching the length of the string, and continues to get zeroes to the necessary length of 14. As long as that "14" in the third line is a lower integer than the number of characters in zeroString, it will work.
function pad(n, len) {
return (new Array(len + 1).join('0') + n).slice(-len);
}
might not work in old IE versions.
//to: 0 - to left, 1 - to right
String.prototype.pad = function(_char, len, to) {
if (!this || !_char || this.length >= len) {
return this;
}
to = to || 0;
var ret = this;
var max = (len - this.length)/_char.length + 1;
while (--max) {
ret = (to) ? ret + _char : _char + ret;
}
return ret;
};
Usage:
someString.pad(neededChars, neededLength)
Example:
'332'.pad('0', 6); //'000332'
'332'.pad('0', 6, 1); //'332000'
An approach I like is to add 10^N to the number, where N is the number of zeros you want. Treat the resultant number as a string and slice off the zeroth digit. Of course, you'll want to be careful if your input number might be larger than your pad length, but it's still much faster than the loop method:
// You want to pad four places:
>>> var N = Math.pow(10, 4)
>>> var number = 1310
>>> number < N ? ("" + (N + number)).slice(1) : "" + number
"1310"
>>> var number = 120
>>> number < N ? ("" + (N + number)).slice(1) : "" + number
"0120"
>>> var number = 10
>>> number < N ? ("" + (N + number)).slice(1) : "" + number
"0010"
…
etc. You can make this into a function easily enough:
/**
* Pad a number with leading zeros to "pad" places:
*
* #param number: The number to pad
* #param pad: The maximum number of leading zeros
*/
function padNumber(number, pad) {
var N = Math.pow(10, pad);
return number < N ? ("" + (N + number)).slice(1) : "" + number
}
I wrote a general function for this. It takes an input control and pad length as input.
function padLeft(input, padLength) {
var num = $("#" + input).val();
$("#" + input).val(('0'.repeat(padLength) + num).slice(-padLength));
}
With RegExp/JavaScript:
var number = 7;
number = ('0000'+number).match(/\d{4}$/);
console.log(number);
With Function/RegExp/JavaScript:
var number = 7;
function padFix(n) {
return ('0000'+n).match(/\d{4}$/);
}
console.log(padFix(number));
No loop, no functions
let n = "" + 100;
let x = ("0000000000" + n).substring(n.length);//add your amount of zeros
alert(x + "-" + x.length);
Nate as the best way I found, it's just way too long to read. So I provide you with 3 simples solutions.
1. So here's my simplification of Nate's answer.
//number = 42
"0000".substring(number.toString().length, 4) + number;
2. Here's a solution that make it more reusable by using a function that takes the number and the desired length in parameters.
function pad_with_zeroes(number, len) {
var zeroes = "0".repeat(len);
return zeroes.substring(number.toString().length, len) + number;
}
// Usage: pad_with_zeroes(42,4);
// Returns "0042"
3. Here's a third solution, extending the Number prototype.
Number.prototype.toStringMinLen = function(len) {
var zeroes = "0".repeat(len);
return zeroes.substring(self.toString().length, len) + self;
}
//Usage: tmp=42; tmp.toStringMinLen(4)
Use String.JS librairy function padLeft:
S('123').padLeft(5, '0').s --> 00123

Categories