ToFixed function on ActionScript/Javascript - javascript

First time in stackoverflow, but I really need help on reconstructing this string.
So basically its in Actionscript and I'd need to reconstruct the Millions-string to output as 1.23M, AKA contain millions with thousands beside it as currently it only shows 1M. I have heard that toFixed would do the trick, but I can't seem to get it to work as my favour.
Any examples would help, thank you!
public static function balanceToString(value:int):String
{
var suffix:String = "";
var resultValue:int = value;
if (value >= 1000000)
{
resultValue = Math.floor(resultValue / 1000000);
resultValue.toFixed(4);
suffix = "M";
}
else if (value >= 100000)
{
resultValue = Math.floor(resultValue / 1000);
suffix = "K";
}
return "" + resultValue.toString() + suffix;
}

You are converting your number to int in the signature.
Try using a Number instead.
public static function balanceToString(value:Number):String
{
var suffix:String = "";
var resultValue:Number = value;
if (value >= 1000000)
{
resultValue = Math.floor(resultValue / 1000000);
resultValue.toFixed(4);
suffix = "M";
}
else if (value >= 100000)
{
resultValue = Math.floor(resultValue / 1000);
suffix = "K";
}
return "" + resultValue.toString() + suffix;
}

Something like this, I guess.
Implementation:
public static function balanceToString(value:int):String
{
var suffix:String = "";
var divisor:Number = 1;
var precision:Number = 0;
if (value >= 100000)
{
// This will display 123456 as 0.12M as well.
divisor = 1000000;
precision = 2;
suffix = "M";
}
else if (value >= 500)
{
// This will display 543 as 0.5K.
divisor = 1000;
precision = 1;
suffix = "K";
}
// This allows you to control, how many digits to display after
// the dot . separator with regard to how big the actual number is.
precision = Math.round(Math.log(divisor / value) / Math.LN10) + precision;
precision = Math.min(2, Math.max(0, precision));
// This is the proper use of .toFixed(...) method.
return (value / divisor).toFixed(precision) + suffix;
}
Usage:
trace(balanceToString(12)); // 12
trace(balanceToString(123)); // 123
trace(balanceToString(543)); // 0.5K
trace(balanceToString(567)); // 0.6K
trace(balanceToString(1234)); // 1.2K
trace(balanceToString(12345)); // 12K
trace(balanceToString(123456)); // 0.12M
trace(balanceToString(1234567)); // 1.23M
trace(balanceToString(12345678)); // 12.3M
trace(balanceToString(123456789)); // 123M

Related

parseInt value from input and use as a check for the sum of last value with Javascript

Trying to track the numbers in an input value and use these as a checkdigit for the last number. Basically, grab the first nine digits of the input, run some simple math and then add those numbers together. Take that total, divide by two then use the remainder as the check digit.
Thus far unsuccessful so if anyone has a good idea of where I am going wrong would gladly appreciate it. I put a fiddle up here: Das Fiddle
window.onkeyup = keyup;
var inputTextValue;
function keyup(e) {
inputTextValue = e.target.value;
$('#numberValue').text(inputTextValue);
// must be 10 characters long
if (inputTextValue.length !== 10) {
return false;
}
// run the checksum
var valid = false;
try {
var sum = (parseInt(inputTextValue[0], 10) * 2) +
(parseInt(inputTextValue[1], 10) * 3) +
(parseInt(inputTextValue[2], 10) * 4) +
(parseInt(inputTextValue[3], 10) * 2) +
(parseInt(inputTextValue[4], 10) * 3) +
(parseInt(inputTextValue[5], 10) * 4) +
(parseInt(inputTextValue[6], 10) * 2) +
(parseInt(inputTextValue[7], 10) * 3) +
(parseInt(inputTextValue[8], 10) * 4);
var checkNumber = 0;
if ((sum % 10) > 0) {
checkNumber = (sum % 10).toFixed(-1);
}
if (inputTextValue[9] === ("" + checkNumber)) {
valid = true;
alert(checkNumber)
}
} catch (e) {
valid = false;
}
return valid;
}
You should be using :
checkNumber = (sum % 10).toFixed(0);
toFixed(-1) will return 0.
Fiddle here

How can I have the value round up in javascript?

I have a code that is inserting the total value into a textbox, however, the math that is performed does not round the number. Based on the code below how can I make this happen?
function calculate(){
var mrc = document.getElementById('box1');
var days = document.getElementById('box2');
var total = document.getElementById('box3');
var reason = document.getElementById('box4');
var approver = document.getElementById('box5');
var approvalreason = document.getElementById('box6');
var custname = document.getElementById('box7');
var caseid = document.getElementById('box8');
var intermitent = document.getElementById('rb1');
var outage = document.getElementById('rb2');
if (outage.checked === true) {
if (days.value * 5 > mrc.value){
total.value = (mrc.value / 30) * days.value;
} else if (days.value > 14) {
total.value = (mrc.value / 30) * days.value;
} else {
total.value = days.value * 5;
}
} else if (intermitent.checked === true){
if (days.value * 3 > mrc.value)
{
total.value = (mrc.value / 30) * days.value;
} else if (days.value > 14) {
total.value = (mrc.value / 30) * days.value;
} else {
total.value = days.value * 3;
}
}
}
Two things:
You're playing with fire by using implicit type conversion. element.value returns a string, not a number, so you should be using parseInt() or parseFloat() to convert your values to numbers. For instance, if your input has value 3, and you do element.value + 2, the result is 32.
Second, to your question, Math.ceil() rounds a float up to the near integer.
Use round() method to rounds a number to the nearest integer.
Example:
var a = Math.round(8.70);
Answer a = 9;
Try the following code:
function toFixed(value, precision) {
var precision = precision || 0,
power = Math.pow(10, precision),
absValue = Math.abs(Math.round(value * power)),
result = (value < 0 ? '-' : '') + String(Math.floor(absValue / power));
if (precision > 0) {
var fraction = String(absValue % power),
padding = new Array(Math.max(precision - fraction.length, 0) + 1).join('0');
result += '.' + padding + fraction;
}
return result;
}
alert(toFixed(1.0000000,3));
Following is the fiddle link:
Demo

Finding Prime Number

JavaScript:
var UI; // Number entered by user
var TV; // Number value to be used in calculations
var HITS; // Counter
var DD; // Division denominator
UI = window.prompt("Enter a whole number to be tested as a prime number", "0");
TV = parseInt("UI", [10]);
HITS = 0;
DD = TV;
while (DD > 0) {
if (TV % DD == 0) {
HITS++
}
HITS--
}
window.document.write(+UI + " is ");
if (HITS > 2) {
window.document.write(" not");
}
window.document.write(" a prime number.");
Can anyone tell me what I'm doing wrong? Everything runs except when it isn't a prime number it the "not" string won't come up. Any help is greatly appreciated.
UI = window.prompt("Enter a whole number to be tested as a prime number", "0");
TV = parseInt(UI,10);
HITS = 0;
DD = TV;
while(DD>0) {
if (TV%DD===0) {
HITS++; }
DD--;
}
I changed this much of and it works now.
//FOR user FOON
PrimeNumber=function(){
var d, l, primelist;
_isPrimeNumber = function(n){
var result = true;
_setVariables(n);
while( d < l ){
if(n % d == 0){
result = false;
break;
}
do{
d = d + 1;
}while(!_check(d));
primelist.push(d);
l = n/d;
}
return result;
};
_getAllPrimeTill = function(n){
_setVariables(n);
while( d < n ){
d = d + 1;
if(_check(d)){
primelist.push(d);
}
}
return primelist;
};
_setVariables = function(n){
d=2;
l=n/2;
primelist = new Array();
primelist.push(d);
};
_check = function(n){
var result = true;
for(var i = 0; i < primelist.length; i++){
if(n % primelist[i] == 0 ){
result = false;
break;
}
}
return result;
};
return {
isPrimeNumber :_isPrimeNumber,
getAllPrimeTill : _getAllPrimeTill
};
}();
You have:
DD = TV;
// The value of DD is tested, but not modified in the loop
while(DD>0) {
// This part is irrelevant to the test
if (TV%DD == 0) {
HITS++
}
HITS--
}
DD is not modified in the loop, so if the condition is true or false, it will always be true or false. So if DD is any value greater than zero, the condition is always true.
import java.util.ArrayList;
import java.util.List;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*if you want to find all prime numbers between 2 and n, change loop "while( d < l ){" to "while( d < n ){" and you will get al prime numbers in primelist.
*/
/**
*
* #author hp
*/
public class PrimeNumber {
public static void main(String[] args) {
String result = " IS A PRIME NUMBER";
int n = 127;
int d = 2;
int l = n / 2;
List <Integer> primelist = new ArrayList<Integer>();
while( d < l ){
if(n % d == 0){
//System.out.println();
//System.out.println(n + " can be divided by " + d);
//System.out.println(d + " * " + (n / d) + " = " + n);
result = " IS NOT A PRIME NUMBER";
break;
}
do{
d = d + 1;
}while(!isPrimeNumber(d,primelist));
//System.out.print(d + ", ");
primelist.add(new Integer(d));
l = n/d;
}
//System.out.println();
System.out.println(n + result);
}
private static boolean isPrimeNumber(int n, List <Integer> primelist){
boolean result = true;
for(Integer i : primelist){
if(n % i.intValue() == 0 ){
result = false;
}
}
return result;
}
}

Add or Subtract From 64bit Integer in Javascript

Is there a simple way (hoping for a small function, not a library) to add or subtract from a 64bit integer in JavaScript?
Example 64bit int: 291270990346989568
Background: I am working with the Twitter API which has 64bit tweet ID's. I'd like to add or subtract one from those IDs to manipulate what results I get back from Twitter.
The following code does what you've described.
Splitting, adding or subtracting, then re-joining...
This code has both increment and decrement functions, and a test function with some edge cases. When splitting number strings and doing math on them, you need to consider what happens to "leading zeroes", so there's a padding function for that.
Thanks, Justin, for providing a JSFiddle with this solution.
/*
* Prepend zeros to expand a given string to given length
*
* #var {String} numStr Number
* #var {Number} len Length to pad out to
*
* #returns {String}
*/
function pad0 (numStr,len) {
while (numStr.length < len) {
numStr = "0" + numStr;
}
return numStr
}
/*
* Decrement the given (64 bit) integer.
*
* #var {String} int64 Postive non-zero integer, as a string
*
* #returns {String}
*/
function decrInt64 (int64) {
var result = "";
var midpt = Math.floor(int64.length/2);
var upper = int64.substring(0,midpt);
var lower = int64.substring(midpt);
var upperVal = new Number(upper);
var lowerVal = new Number(lower);
if (lowerVal == 0) {
if (upperVal == 0) {
// We don't support negative numbers
result = "*ERROR*"
}
else {
// borrow 1
result = pad0((--upperVal).toString(),upper.length) +
(new Number("1"+lower) - 1).toString();
}
}
else {
var newLower = (lowerVal - 1).toString();
result = upper + pad0(newLower,lower.length);
}
alert(result);
}
/*
* Increment the given (64 bit) integer.
*
* #var {String} int64 Postive, as a string
*
* #returns {String}
*/
function incrInt64 (int64) {
var result = "";
var midpt = Math.floor(int64.length/2);
var upper = int64.substring(0,midpt);
var lower = int64.substring(midpt);
var upperVal = new Number(upper);
var lowerVal = new Number(lower);
var newLower = (++lowerVal).toString();
// Did we overflow?
if (lower.length < newLower.length) {
// Yes, carry the 1
result = (++upperVal).toString() + newLower.substring(1);
}
else {
result = upper + pad0(newLower,lower.length);
}
alert(result);
}
// Test function
window.displaymessage= function ()
{
decrInt64("291270990046989568");
incrInt64("291270990046989568");
decrInt64("000000000000000000");
incrInt64("000000000000000000");
decrInt64("000000001000000000");
incrInt64("000000001000000000");
decrInt64("099999999999999999");
incrInt64("099999999999999999");
decrInt64("999999999999999999");
incrInt64("999999999999999999");
}
Addition of integer-formatted strings (base 10) of indefinite lengths can be done by splitting the string into segments of 9 characters, calculating + or - for that and then moving to the preceding 9 characters. This is because the largest 9 character number, 999999999 is 32-bit safe (as is 1999999999, which I used in subtraction).
The following code has 3 functions and the word integer is assumed to mean an integer-formatted string.
addAsString, takes two non-negative integers x and y, returns x + y
subtractAsString, takes two non-negative integers x and y, |x| >= |y|, returns x - y
addORsub, takes any two integers x and y, returning x + y
I've tried to explain what is happening via comments in the code
// Indefinate length addition
function addAsString(x, y) { // x, y strings
var s = '';
if (y.length > x.length) { // always have x longer
s = x;
x = y;
y = s;
}
s = (parseInt(x.slice(-9),10) + parseInt(y.slice(-9),10)).toString(); // add last 9 digits
x = x.slice(0,-9); // cut off last 9 digits
y = y.slice(0,-9);
if (s.length > 9) { // if >= 10, add in the 1
if (x === '') return s; // special case (e.g. 9+9=18)
x = addAsString(x, '1');
s = s.slice(1);
} else if (x.length) { // if more recursions to go
while (s.length < 9) { // make sure to pad with 0s
s = '0' + s;
}
}
if (y === '') return x + s; // if no more chars then done, return
return addAsString(x, y) + s; // else recurse, next digit
}
// Indefinate length subtraction (x - y, |x| >= |y|)
function subtractAsString(x, y) {
var s;
s = (parseInt('1'+x.slice(-9),10) - parseInt(y.slice(-9),10)).toString(); // subtract last 9 digits
x = x.slice(0,-9); // cut off last 9 digits
y = y.slice(0,-9);
if (s.length === 10 || x === '') { // didn't need to go mod 1000000000
s = s.slice(1);
} else { // went mod 1000000000, inc y
if (y.length) { // only add if makes sense
y = addAsString(y, '1');
} else { // else set
y = '1';
}
if (x.length) {
while (s.length < 9) { // pad s
s = '0' + s;
}
}
}
if (y === '') { // finished
s = (x + s).replace(/^0+/,''); // dont return all 0s
return s;
}
return subtractAsString(x, y) + s;
}
// Indefinate length addition or subtraction (via above)
function addORsub(x, y) {
var s = '';
x = x.replace(/^(-)?0+/,'$1').replace(/^-?$/,'0'); // -000001 = -1
y = y.replace(/^(-)?0+/,'$1').replace(/^-?$/,'0'); // -000000 = 0
if (x[0] === '-') { // x negative
if (y[0] === '-') { // if y negative too
return '-' + addAsString(x.slice(1), y.slice(1)); // return -(|x|+|y|)
}
return addORsub(y, x); // else swap
}
if (y[0] === '-') { // x positive, y negative
s = y.slice(1);
if (s.length < x.length || (s.length === x.length && s < x)) return subtractAsString(x, s) || '0'; // if |x|>|y|, return x-y
if (s === x) return '0'; // equal then 0
s = subtractAsString(s, x); // else |x|<|y|
s = (s && '-' + s) || '0';
return s; // return -(|y|-x)
}
return addAsString(x, y); // x, y positive, return x+y
}
Example usage (fiddle)
var i = addORsub('291270990346989568', '1'); // add
i === '291270990346989569';
i = addORsub('291270990346989568', '-1'); // subtract
i === '291270990346989567';

Convert integer to alpha ordered list equivalent

I need to a function to convert an integer to the equivalent alpha ordered list index. For example:
1 = a
2 = b
.
.
.
26 = z
27 = aa
28 = ab
.
.
etc.
Currently I have the following which almost works but there's a small logic error somewhere that makes it not quite get it right (it goes ax, ay, bz, ba, bb, bc...):
function intToAlpha( int ) {
var asciiStart = 97,
alphaMax = 26,
asciiCode,
char,
alpha = '',
place,
num,
i;
for ( i = 0; Math.pow(alphaMax, i) < int; i++ ) {
place = Math.pow(alphaMax, i);
num = Math.floor( ( int / place ) % alphaMax);
asciiCode = ( num == 0 ? alphaMax : num ) + asciiStart - 1;
char = String.fromCharCode(asciiCode);
alpha = char + alpha;
}
return alpha;
}
for (i = 1; i < 300; i++) {
console.log( i + ': ' + intToAlpha(i) );
}
This function is used in NVu/Kompozer/SeaMonkey Composer, with a small tweak to generate lower case directly:
function ConvertArabicToLetters(num)
{
var letters = "";
while (num > 0) {
num--;
letters = String.fromCharCode(97 + (num % 26)) + letters;
num = Math.floor(num / 26);
}
return letters;
}
You need to make sure that you use the correct value when taking the mod.
function intToAlpha( int ) {
var asciiStart = 97,
alphaMax = 26,
asciiCode,
char,
alpha = "";
while(int > 0) {
char = String.fromCharCode(asciiStart + ((int-1) % alphaMax));
alpha = char + alpha;
int = Math.floor((int-1)/26);
}
return alpha;
}
A while back I needed the same thing in SQL, so I asked (and answered) the question Multi-base conversion - using all combinations for URL shortener.
The thing that is making it complicated is that it's not a straight base conversion, as there is no character representing the zero digit.
I converted the SQL function into Javascript:
function tinyEncode(id) {
var code, value, adder;
var chars = 'abcdefghijklmnopqrstuvwxyz';
if (id <= chars.length) {
code = chars.substr(id - 1, 1);
} else {
id--;
value = chars.length;
adder = 0;
while (id >= value * (chars.length + 1) + adder) {
adder += value;
value *= chars.length;
}
code = chars.substr(Math.floor((id - adder) / value) - 1, 1);
id = (id - adder) % value;
while (value > 1) {
value = Math.floor(value / chars.length);
code += chars.substr(Math.floor(id / value), 1);
id = id % value;
}
}
return code;
}
Demo: http://jsfiddle.net/Guffa/mstBe/

Categories