From b8af4a444a7998bff75fd3769cfb740108a24cc1 Mon Sep 17 00:00:00 2001 From: username01010100 Date: Tue, 9 Jan 2024 17:29:59 +0700 Subject: [PATCH] fix: float decimal (single-percision) detection --- lib/BufferEncoder.js | 5 ++--- test/BufferEncoder.test.js | 4 ++-- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/lib/BufferEncoder.js b/lib/BufferEncoder.js index c8ea534..bc36b44 100644 --- a/lib/BufferEncoder.js +++ b/lib/BufferEncoder.js @@ -92,11 +92,10 @@ BufferEncoder.prototype.encode = function(key, val, index) { * @param {Number} index */ BufferEncoder.prototype._asFloat = function(val, index) { - // TODO: bad detection - var valLen = val.toString().split('.')[1].length; + var isFloat32 = (Math.fround(val) === val); // Float. - if (valLen <= 6) { + if (isFloat32) { this._setMark(marks.DEFAULT_MARK_FLOAT, index); this._toFloat32(val); } diff --git a/test/BufferEncoder.test.js b/test/BufferEncoder.test.js index f60bd46..c1bc7ab 100644 --- a/test/BufferEncoder.test.js +++ b/test/BufferEncoder.test.js @@ -114,8 +114,8 @@ describe("BufferEncoder", () => { expect(bufferEncoder._offset).toBe(16); }); - it("encodes 1.234567 as 5 bytes (float with mark)", () => { - bufferEncoder.encode(undefined, 1.234567); + it("encodes 123.45600128173828 as 5 bytes (float with mark)", () => { + bufferEncoder.encode(undefined, 123.45600128173828); expect(bufferEncoder._offset).toBe(5); });