Posts

Showing posts with the label Floating Point

BigDecimal In JavaScript

Answer : I like using accounting.js for number, money and currency formatting. Homepage - https://openexchangerates.github.io/accounting.js/ Github - https://github.com/openexchangerates/accounting.js

C Function To Convert Float To Byte Array

Answer : Easiest is to make a union: #include <stdio.h> int main(void) { int ii; union { float a; unsigned char bytes[4]; } thing; thing.a = 1.234; for (ii=0; ii<4; ii++) printf ("byte %d is %02x\n", ii, thing.bytes[ii]); return 0; } Output: byte 0 is b6 byte 1 is f3 byte 2 is 9d byte 3 is 3f Note - there is no guarantee about the byte order… it depends on your machine architecture. To get your function to work, do this: void float2Bytes(byte bytes_temp[4],float float_variable){ union { float a; unsigned char bytes[4]; } thing; thing.a = float_variable; memcpy(bytes_temp, thing.bytes, 4); } Or to really hack it: void float2Bytes(byte bytes_temp[4],float float_variable){ memcpy(bytes_temp, (unsigned char*) (&float_variable), 4); } Note - in either case I make sure to copy the data to the location given as the input parameter. This is crucial, as local variables will not exist after you return (alt...

Best Way To Parse Float?

Answer : I agree with leppie's reply; to put that in terms of code: string s = "123,456.789"; float f = float.Parse(s, CultureInfo.InvariantCulture); Depends where the input is coming from. If your input comes from the user, you should use the CultureInfo the user/page is using (Thread.CurrentThread.CurrentUICulture). You can get and indication of the culture of the user, by looking at the HttpRequest.UserLanguages property. (Not correct 100%, but I've found it a very good first guess) With that information, you can set the Thread.CurrentThread.CurrentUICulture at the start of the page. If your input comes from an internal source, you can use the InvariantCulture to parse the string. The Parse method is somewhat easier to use, if your input is from a controlled source. That is, you have already validated the string. Parse throws a (slow) exception if its fails. If the input is uncontrolled, (from the user, or other Internet source) the TryParse looks b...