I need to convert a formatted number to JS default number format.
This is my code:
String.prototype.toJsFloatFormat = function() {
debugger;
var newVal = this;
return newVal;
}
//Example of use
var input = 10000.22; //default js format
var formatted = input.toLocaleString("es"); // result is: 10.000,22
var unformatted = formatted.toJsFloatFormat(); //expected result = 10000.22;
The problem is when I need to get the formatted number (10.000,22) and I make operations with this formatted number (parseFloat(10.000,22) + 1000) I have bad results ( parseFloat(10.000,22) + 1000 = 1010)
thanks in advance.
It's not easy. There's a reason why most of the comments have said "Don't try -
do your calculations on the number itself, not the formatted value".
You need to work out what the decimal and thousand separator characters are. For that, you will need to know which locale the number was converted into.
(1234.5).toLocaleString("es").match(/(\D+)/g);
// -> [".", ","]
Once you have that, you can replace characters in the formatted string.
function unformatString(string, locale) {
var parts = (1234.5).toLocaleString(locale).match(/(\D+)/g);
var unformatted = string;
unformatted = unformatted.split(parts[0]).join("");
unformatted = unformatted.split(parts[1]).join(".");
return parseFloat(unformatted);
}
There is no way of working out the locale - you have to know it and pass it to the function.
no need to reinvent the wheel -
https://github.com/globalizejs/globalize#readme
var input = 10000.22;
Globalize.parseFloat(input );
I did it this way(in my case it was the 'ru' local format, so I did replace the 'space' symbol):
var myNumber = 1000000;
var formated = myNumber.toLocaleString('ru');
var unformated = parseInt(formated.replace(/\s/g, ''));
your case:
var formated = myNumber.toLocaleString('en');
var unformated = parseInt(formated.replace(/,/g, ''));
I did this, that's fine for me
function localeStringToFloat(locale){
if(!locale) return locale
let test=1000
test=test.toLocaleString(undefined,{minimumFractionDigits: 2,maximumFractionDigits: 2});
let separator=test[1]
let decimalSeparator=test[5]
return parseFloat(locale.replaceAll(separator,'').replace(decimalSeparator,'.'))
}
My functions for format and unFormat currency numbers to 'en-US'. I hope helps
function myFormatPrice(num,digits){
return num.toLocaleString('en-US', {maximumFractionDigits:digits});
}
function myUnFormatPrice(formated){
return parseFloat( formated.replaceAll(',','') );
}
Related
var weightkg=document.getElementById('weight').value;
var heightinm=document.getElementById('height').value;
function bmival (weightkg,heightinm){
var hout=heightinm*2
var output=weightkg/hout
//make a full number
// var r= Math.trunc(o)
if (output<=18.5){
return document.getElementById('print').innerHTML=`Your BMI is ${output} you are underweight` ;
}
else if(output>18.5 && o<25.5){
return document.getElementById('print').innerHTML=`Your BMI is ${output} You come under fit catogery`;
}
else{
return document.getElementById('print').innerHTML=`Your BMI is ${output} you are overweight and obese`;
}
}
[i am making a bmi cal that take input from user but i am getting a error and don't know what i am doing wrong]
**
this is js code and when i run i get a NaN instead of Number **
The values from an input field are strings so you must convert them into numbers
var heightinm = +document.getElementById('height').value; // one way to do it.
The value you get from
var weightkg=document.getElementById('weight').value;
seems to be a string instead of number. You need to convert values to do Math operations on them. NaN tells you output is not a number. Turn your values to number with parseInt method.
var weightkg = parseInt(document.getElementById('weight').value);
or you can just put a "+" to convert a string into number
var weightkg = +document.getElementById('weight').value;
For Example.
const input = document.getElementById('input');
const defaultStringInput = document.getElementById('input').value;
const inputConverted = parseInt(document.getElementById('input').value);
const inputConverted2 = +document.getElementById('input').value;
input.addEventListener('change', () => {
console.log(typeof defaultStringInput); // string
console.log(typeof inputConverted); // number
console.log(typeof inputConverted2); // number
});
I am trying to compare two dates as strings in typescript. The input I have is as below :-
startWindow = '05/2014'
endWindow = '05/2018'
I need to write a function to check if the start Window is greater than the end Window.
Both the inputs are of string type.
Thanks
You can convert it to a date and then compare them:
function convertDate(d)
{
var parts = d.split('/');
return new Date(parts[1], parts[0]);
}
var start = convertDate('05/2014');
var end = convertDate('05/2018');
alert(start < end);
I'm trying to do operations in 160 bit integers using the bigInteger.js library, but I want to keep a representation of those in hex format so I can transmit them over and use them as ID.
var git_sha1 = require('git-sha1');
var bigInt = require("big-integer");
var uuid = git_sha1((~~(Math.random() * 1e9)).toString(36) + Date.now());
console.log('in hex \t', uuid); // See the uuid I have
console.log('in dec \t', bigInt(uuid, 16).toString()); // convert it to bigInt and then represent it as a string
console.log('to hex \t', bigInt(uuid, 16).toString(16)); // try to convert it back to hex
Here is my output:
in hex 4044654fce69424a651af2825b37124c25094658
in dec 366900685503779409298642816707647664013657589336
to hex 366900685503779409298642816707647664013657589336
I need that to hex to be the same as in hex. Any suggestions? Thank you!
This was fixed with the PR of https://github.com/peterolson/BigInteger.js/pull/18
I don't know if you're that attached to big-integer, but if you're not, bigint does exactly what you want.
EDIT : If you want to keep big-integer, this should do the trick :
function toHexString(bigInt) {
var output = '';
var divmod;
while(bigInt.notEquals(0)) {
divmod = bigInt.divmod(16);
bigInt = divmod.quotient;
if (divmod.remainder >= 10)
output = String.fromCharCode(87+divmod.remainder) + output;
else
output = divmod.remainder + output;
}
return output;
}
I don't get it.
I can't increment the Tweet-ID ...
Here is a demo: http://jsbin.com/idupoq/1/edit
glb = {};
glb.lastTweetId = 0;
getTweets();
function getTweets()
{
console.info('# LAST ID');
console.log(glb.lastTweetId);
console.info('# TEST 1');
glb.lastTweetId++;
console.log(glb.lastTweetId);
console.info('# TEST 2');
glb.lastTweetId = glb.lastTweetId+1;
console.log(glb.lastTweetId);
console.info('# TEST 3, OK IS INT BUT PARSE AGAIN ');
glb.lastTweetId = parseInt(glb.lastTweetId);
glb.lastTweetId++;
console.log(glb.lastTweetId);
$.getJSON('http://search.twitter.com/search.json?q=%23wwm&since_id='+glb.lastTweetId+'&include_entities=true&result_type=mixed&lang=de&callback=?', function(data, textStatus)
{
if(data.results.length > 0)
{
glb.lastTweetId = data.results[0]['id'];
}
glb.tm= setTimeout('getTweets();',5000);
});
}
Thanks in advance!
This happens because the received ID is out of range of Number format, e.g.
271567725082578940 + 1 = 271567725082578940
You should use special libraries to work with large numbers. Some examples:
https://github.com/jtobey/javascript-bignum
http://jsfromhell.com/classes/bignumber
As others have said already, it is because of Number cannot express 271567725082578941. If all you ever want to do to this number is to increase it by one, then the following function should be all you need:
function stringInc(v){
var digits = v.toString().split('');
var i = digits.length-1;
while (digits[i]==9 && i>0){
digits[i] = 0;
i--;
}
digits[i] = 1+parseInt(digits[i]);
return digits.join('');
}
If you expect to want to do something more with the number, then you might be better off using a BigNumber library as suggested by VisioN.
Either way, you should note that you cannot read the tweet id from data.results[0]['id'], because that is interpreted as a Number and rounded to 271567725082578940. You need to use data.results[0]['id_str'].
See updated jsbin here: http://jsbin.com/idupoq/19/. Notice the console is logging the result from the server:
...
"geo":null,
"id": 271580395022217200,
"id_str":"271580395022217216",
"iso_language_code":"de"
...
So the value 271567725082578940 that you have been observing is incorrect as well.
Dirty but short
http://jsbin.com/idupoq/18/edit
glb.lastTweetId = ''+data.results[0]['id']+'';
var lastTwoDig = parseInt(glb.lastTweetId.substr(glb.lastTweetId.length-2));
var startDigit = glb.lastTweetId.substring(0, glb.lastTweetId.length-2);
lastTwoDig++;
if(lastTwoDig==01){ lastTwoDig = '01'; }
console.log(glb.lastTweetId);
console.log(' '+startDigit+''+lastTwoDig+' ');
I am trying to sum up the following numbers.
var number1= 12,000.00 ; var number2= 12,000.00;
I have tried this alert(number1+number2); but it doesn't return any data.
Could you please help me to solve this problem?
Thanks
The code in your question is invalid javascript. You can't have a , inside a numeric literal. You have to store it as a string, then parse it manually:
var number1 = '12,000.00';
var number2 = '12,000.00';
function parseCurrency( num ) {
return parseFloat( num.replace( /,/g, '') );
}
alert( parseCurrency(number1) + parseCurrency(number2) );
This won't work. Use accounting.js's unformat function to parse 12,000 as a string instead.