I am trying to convert the following JavaScript code to Python:
var n = 0.3846705659431655
n.toString(16)
result: "0.6279c52c75af6"
The challenge I am having right now is that I can't seem to convert floats in Python. It will error on me or give me a different result.
Example:
n = 0.3846705659431655
float.hex(n)
result: 0x1.89e714b1d6bd8p-2
expected result: "0.6279c52c75af6"
Is there any other method for me to get the same result in Python?
I'm doing it with Python 3.8 but it should work also for you.
def FloatToHex(number, base = 16):
if number < 0: # Check if the number is negative to manage the sign
sign = "-" # Set the negative sign, it will be used later to generate the first element of the result list
number = -number # Change the number sign to positive
else:
sign = "" # Set the positive sign, it will be used later to generate the first element of the result list
s = [sign + str(int(number)) + '.'] # Generate the list, the first element will be the integer part of the input number
number -= int(number) # Remove the integer part from the number
for i in range(base): # Iterate N time where N is the required base
y = int(number * 16) # Multiply the number by 16 and take the integer part
s.append(hex(y)[2:]) # Append to the list the hex value of y, the result is in format 0x00 so we take the value from postion 2 to the end
number = number * 16 - y # Calculate the next number required for the conversion
return ''.join(s).rstrip('0') # Join all the list values and return the converted number
n = 0.3846705659431655
print(FloatToHex(n))
result 0.6279c52c75af6
Related
Let's say that I have a list of points declared in this format: x1,y1 x2,y2
listOfPoints : string = "12.2, 13.0 198.2, 141";
What could I do to multiply by 1.5, for example, every number of this string ?
Do I need to iterate over the listOfPoints and extract a string every time that there is a ', ' or ' ', convert that string into a number, multiply it by 1.5 and reconvert it into a string to finally put it into a new string (newListOfPoints) ?
Or is there a different way to that more efficiently ?
Thank you.
Use a regular expression with a replacer function to match digits, possibly with decimals, and replace with those digits multiplied by the number you want:
const listOfPoints = "12.2, 13.0 198.2, 141";
const multiplied = listOfPoints.replace(
/\d+(?:\.\d+)?/g,
match => match * 1.5
);
console.log(multiplied);
Due to floating-point issues, some of the resulting numbers may have trailing digits. If you don't want that, you can round the multiplied number to a certain number of decimal places:
const listOfPoints = "12.2, 13.0 198.2, 141";
const multiplied = listOfPoints.replace(
/\d+(?:\.\d+)?/g,
match => Math.round(1000 * match * 1.5) / 1000
);
console.log(multiplied);
im just about done with an assignment and on the last question I have attempted to do it but I dont know if I used the bitshifting correctly.
For the question, I had to extract the right byte of an integer, then get the first 3 bits, next 3 bits, and last 2 bits of that right byte and assign it to unsigned integer variables.
What I have tried so far is:
int rightmost = (y>>24)&0xFF // to get rightmost byte
int first = (rightmost <<< 1)&0xFF // to get first 3 bits of that byte
int second = (rightmost >>> 3)&0xFF // to get next 3 bits
int third = (rightmost >>> 6)&0xFF // to get last 2 bits
Id just like to know if I am going in the right direction
I'd do this:
var firstByte = y & 0xff;
That's the least-significant byte. If the value in y is 12, all the bits will be in that byte.
Then, to isolate the parts of that byte, you have to use & to chop off all the bits you don't want, and then >> to get the bits into the least-significant positions. The order in which you do that doesn't matter, though it does dictate what you put on the other side of &:
var first3 = firstByte & 0x07; // no need to shift
var second3 = (firstByte >> 3) & 0x07; // shift by 3 and then mask off the rest
var last2 = (firstByte >> 6) & 0x03; // shift by 6 and mask
In binary, 0x07 looks like 00000111. Thus using & with that isolates the least-significant 3 bits in a number.
Test below.
JavaScript is kind-of weird because in between all those operations the language maintains the numbers as 64-bit floating-point values. For integer values however that doesn't really matter, and indeed an optimized runtime may not actually keep the floating point representations around, if it's really smart about things.
var y = 2359; // binary: 100100110111
var firstByte = y & 0xff;
console.log("firstByte: " + firstByte);
var first3 = firstByte & 0x07;
console.log("should be 7: " + first3); // should be 7
var second3 = (firstByte >> 3) & 0x07;
console.log("should be 6: " + second3); // should be 6
var last2 = (firstByte >> 6) & 0x03;
console.log("should be 0: " + last2); // should be 0
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)
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 ,.
I am trying to add numbers as strings using basic math. I first set the local storage to "0" then add "1" to it each time. I feel I am on the right path, but when I run this my result is not 0 + 1 = 1 rather I get "01" in my local storage. I want to be able to add 1 to the existing local storage each time so 0 + 1 I get 1. Next time around 1 + 1 I get 2, and 2 + 1 I get 3 and so on.
// sets "points" to 0 when user first loads page.
if (localStorage.getItem("points") === null){
localStorage.setItem("points", "0");
}
// get points
var totalPoints = localStorage.getItem("points");
// add 1 points to exisiting total
var addPoint = totalPoints +"1";
// set new total
localStorage.setItem("points", addPoint);
You can convert a string to a number in several ways (not an exhaustive list):
var n = s * 1; // s is the string
var n = s - 0;
var n = parseFloat(s);
var n = Number(s);
var n = ~~s; // force to 32-bit integer
var n = parseInt(s, 10); // also integer, precise up to 53 bits
Convert your strings to numbers when you fetch them from local storage, do the math, and then put the results back.
edit — the thing to keep in mind is that + is more "interesting" than the other arithmetic operators because it has meaning for string-valued operands. In fact, JavaScript tends to prefer string interpretation of the + operator, so if there's a string on one side and a number on the other, the operation is string concatenation and not arithmetic addition.