Convert localized string into decimal in javascript - javascript

I have a decimal, that could look like 123,34, 123123,09, 1234, 123.34, 123123.09.
My MVC application supports localization, I need to find a safe way to convert the most likely user input into a decimal. So for decimal value . will represent as , (e.g 12.34 => 12,34)
I want to get this value in javascript as
var maxAmount = parseFloat("#Model.MaxAmount");
if MaxAmount is 1,25 I will get a result as 1 only.
How is that possible?

Why not specify the format for the model property using MaxAmount.ToString(CultureInfo.InvariantCulture) - that way the decimal will always be serialized as 1.25 and still be properly interpreted by JavaScript.

Just do the replace for the edge case of xxx,xx:
var maxAmount = parseFloat('#Model.MaxAmount'.replace(',', '.'));
This will convert string of type "123,45" to "123.45" but keep the "123.45" in the same format.

Related

Maintain decimal points with 0 in JSON object [duplicate]

If you do this...
var parsed = JSON.parse('{"myNum":0.0}') ;
Then when you look at parsed.myNum, you just get 0. (Fair enough.)
If you do parsed.myNum.toString(), you get "0".
Basically, I'm looking for a way to turn this into the string "0.0".
Obviously, in real life I don't control the JSON input, I get the JSON from a web service... I want to parse the JSON using the browser's JSON parser, and to be able to recognise the difference between the number values 0 and 0.0.
Is there any way to do this, short of manually reading the JSON string? That's not really possible in this case, I need to use the browser's native JSON parser, for speed. (This is for a Chrome extension by the way; no need to worry about it working in other browsers.)
There's no way to get the number of digits from JSON.parse or eval. Even if IBM's decimal proposal had been adopted by the EcmaScript committee, the number is still going to be parsed to an IEEE 754 float.
Take a look a http://code.google.com/p/json-sans-eval/source/browse/trunk/src/json_sans_eval.js for a simple JSON parser that you can modify to keep precision info.
If 0.0 is not enclosed in quotes in your JSON (i.e. it's a number and not a string), then there's no way to distinguish it from 0, unless you write your own JSON parser.
... parsed.myNum.toFixed( 1 ) ...
where 1 is number of decimal places
Edit: parsed.myNum is number, parsed.myNym.toFixed( 1 ) would be string
Edit2: in this case you need to pass value as string {"myNum":'0.0'} and parsed when calculations is needed or detect decimal separator, parsed number, and use decimal separator position when string is needed
It shouldn't matter, 00000.00000 is 0 if you try JSON.parse('{"myNum":0.00001}') you'll see a value of { myNum=0.0001 } If you really need it to hold the decimal you'll need to keep it a string JSON.parse('{"myNum":"0.0"}')

Number.toString returns "incorrect" hexadecimal value

In order to utilize a third party API, I have to convert the ID number to a hexadecimal. I converted the ID with https://www.rapidtables.com/convert/number/decimal-to-hex.html and got 711DD21A11FA9223FEB43849FF1F3569DC024DCE000000000000150000000001. This works when I use it with the API.
My understanding is that you can perform the same conversion with JS with Number().toString(16). However, when I use that function I get 711dd21a11fa9400000000000000000000000000000000000000000000000000.
The latter value does not work with the API. Any insight into why the JS function returns a different value?
Your number is too big for JavaScript.
The Number.MAX_SAFE_INTEGER constant represents the maximum safe integer in JavaScript.
I advise you to use the BigInt data type.
BigInt is a primitive wrapper object used to represent and manipulate primitive bigint values - which are too large to be represented by the number primitive.
Exampe:
// Your number in decimal
const decimalNumber = BigInt("10000000000000000");
// Your number in hex
const hexNumber = decimalNumber.toString(16);
console.log(`Decimal number: ${decimalNumber}`);
console.log(`Hex number: ${hexNumber}`);

Why my session value changed for a particular value?

Can someone help understand why my session value changed for a particular value, 03375?
My MVC controller code:
Session["something"] = "03375";
My view js code:
$(function(){
alert(#Session["something"].ToString());
});
Result: js alerts 1789. Why???
It works for other values except. Here is a fiddle https://dotnetfiddle.net/zLdyO8
This has nothing to do with asp.net session. If you do this in your page
console.log(03375);
You will get 1789
Why is this happening ?
Because when browser's javascript runtime sees a number starting with 0 prefix, it thinks it is octal representation of the number. In fact 03375 is the octal equivalent of 1789. So your browser is basically converting the octal value
to it's decimal equivalent and giving you 1789 (browsers usually parse the number to decimal representation)
From mdn,
Note that decimal literals can start with a zero (0) followed by
another decimal digit, but if every digit after the leading 0 is
smaller than 8, the number gets parsed as an octal number.
This means, if you are trying
console.log(09375);
It will print,9375 !!!
To handle your case, the ideal solution is to set the correct type value. For example, if you are passing a numeric value, simply set the numeric value instead of the string version with leading zero..
Session["something"] = "3375";
Or even better
Session["something"] = 3375;
Then in the client side,
alert(#Session["something"]);
If you absolutely want to keep the 0 prefix, while setting the session value, but you want the value as number at client side, you can read it in a string and then use parseInt to convert it to a number type
var r = '#Session["something"].ToString()';
alert(r); // the string with leading 0
var n = parseInt(r);
alert(n); // the number
alert(typeof(n));

Convert to string nodejs

0xc4115 0x4cf8
Im not sure what data type this is so my question would be:
What data type is this and how can I convert it to something more manageable using NODE.JS?
you can convert Hexadecimal to Decimal by this
let hex_num = "0xc4115";
console.log(Number(hex_num)); #803093
In general you have the format 0x for hexadecimal, 0b for binary and 0 for octal. All this represent Numbers. JavaScript converts to decimal all of this types automatically. In case you want to do it yourself, you can use parseInt(number,base).

Convert number in javascript produces NAN

I have a text box whose outcome is in Belgium number format like this
<input type="text" name="valeurCatalogue" kendo-numeric-text-box="" k-culture='"fr-BE"' k-spinners="{{false}}" ng-disabled="isValueCatalogDisabled" ng-model="tarifForm.Vehicle.valeurCatalogue" />
Having put the value as 1525,8 the value gets transformed to 1.525,80 which is correct.
Now if I apply Number(1525,8) I get NAN.How to get the number in javascript?
Please note in debug mode I see the value 1525,8 as string.
The problem here is that javascript uses the american way of expressing numbers (as do most programming languages I've encountered). So, 1,5 is not one and a half as you would expect, rather it's not a valid number. Thus when you try to parse it you get NaN (Not a Number). In javascript, the correct way to write said number would be 1.5. If you have 1525,8 the simple way to do this is replace all commas with dots like this:
const numStr = '1525,8';
const replaced = numStr.replace(/,/, '.');
const num = Number(replaced);
If however, your number is 1.525,8 you need to first remove the dots (str.replace(/\./g, '');).

Categories

Resources