floatToU8a adjustment (#1549)

This commit is contained in:
Jaco
2022-06-19 21:29:34 +03:00
committed by GitHub
parent 4fd4660853
commit b4d65a1c49
2 changed files with 28 additions and 16 deletions
+24
View File
@@ -35,6 +35,30 @@ describe('floatToU8a', (): void => {
u8aToHex(floatToU8a(Number.NaN, { isLe: true }))
).toEqual('0x0000c07f');
});
describe('equivalency', (): void => {
it('encodes number 123.456', (): void => {
expect(
u8aToHex(floatToU8a(123.456))
).toEqual('0x79e9f642');
});
it('encodes string 123.456', (): void => {
expect(
u8aToHex(floatToU8a('123.456'))
).toEqual('0x79e9f642');
});
it('encodes Number 123.456', (): void => {
class Test extends Number {
foo = 'bar';
}
expect(
u8aToHex(floatToU8a(new Test(123.456)))
).toEqual('0x79e9f642');
});
});
});
describe('64-bit', (): void => {
+4 -16
View File
@@ -1,8 +1,6 @@
// Copyright 2017-2022 @polkadot/util authors & contributors
// SPDX-License-Identifier: Apache-2.0
import { isString } from '../is/string';
// eslint-disable-next-line @typescript-eslint/ban-types
type AnyFloat = number | Number;
@@ -16,7 +14,7 @@ interface Options {
* @description Converts a float into a U8a representation (While we don't use BE in SCALE
* we still allow for either representation, although, as elsewhere, isLe is default)
*/
export function floatToU8a (value: string | AnyFloat = '0.0', { bitLength = 32, isLe = true }: Options = {}): Uint8Array {
export function floatToU8a (value: string | AnyFloat = 0.0, { bitLength = 32, isLe = true }: Options = {}): Uint8Array {
if (bitLength !== 32 && bitLength !== 64) {
throw new Error('Invalid bitLength provided, expected 32 or 64');
}
@@ -24,20 +22,10 @@ export function floatToU8a (value: string | AnyFloat = '0.0', { bitLength = 32,
const result = new Uint8Array(bitLength / 8);
const dv = new DataView(result.buffer, result.byteOffset);
if (value instanceof Number) {
value = value.toString();
}
if (isString(value)) {
if (bitLength === 32) {
dv.setFloat32(0, parseFloat(value), isLe);
} else {
dv.setFloat64(0, parseFloat(value), isLe);
}
} else if (bitLength === 32) {
dv.setFloat32(0, value, isLe);
if (bitLength === 32) {
dv.setFloat32(0, Number(value), isLe);
} else {
dv.setFloat64(0, value, isLe);
dv.setFloat64(0, Number(value), isLe);
}
return result;